Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get session cookies from express-session in React

My node.js server is using express-session for authentication.

const express = require('express')
const session = require('express-session')

const app = express()

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://192.168.1.24:3000");
    res.header("Access-Control-Allow-Credentials", 'true')
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
})

app.use(session({ secret: 'neverGotWhatShouldBeHere', resave: false, saveUninitialized: false }))

app.get('/login', (req, res) => {
    req.session.userAuth = "some data"
    req.session.cookie.maxAge = 10 * 1000
    res.send({ prob: 'no' })
})

app.get('/restricted', (req, res) => {
    if (req.session.userAuth == "some data")
        res.send({ prob: 'no', data: 'top secret confidential data' })
    else
        res.send({ prob: 'log in to see data' })
})

app.listen(3000, () => console.log(`Example app listening at http://localhost:3000`))

When I access it from the browser, all works well. I can see the cookie and it disappears 10 seconds later, forcing me to log in again.

Then I created a React application using create-react-app.

App.js:

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  remoteLogin = () => {
    fetch('http://192.168.1.25/login', { credentials: 'include' }).then((response) => {
      return response.json().then((jsonResponse) => {
        console.log(jsonResponse)
      }).catch((err) => {
        console.log("Error: " + err)
      })
    })
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.remoteLogin} >Log in</button>
      </div>
    )
  }
}

export default App;

When I click the button, I see the json data from the server, but I get no cookie.

How can I get the cookie in the React application?

like image 887
Matan Livne Avatar asked Oct 24 '25 02:10

Matan Livne


1 Answers

Dont know if it help you, but i use react-cookie for my session cookies :

https://www.npmjs.com/package/react-cookies

You just save your cookie with all the data you want,only with react

like image 179
Jonathan Delean Avatar answered Oct 27 '25 02:10

Jonathan Delean