MD10
MD10

Reputation: 1521

Cannot retrieve cookies from react request

Here is my react code:

axios.get('http://localhost:5000/check').then(() => {
      axios.post('http://localhost:5000/cookie', null, { withCredentials: true });
    });

backend node js:

import express, { Application, Request, Response } from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';

const app: Application = express();

app.use(cookieParser());
app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/check', (req, res) => {
  res.cookie('token', 'asdasd3123123', { httpOnly: true });
  res.send(200);
});

app.post('/cookie', (req: Request, res) => {
  console.log(JSON.stringify(req.cookies));
  res.send();
});

app.listen(5000, () => {
  console.log('Server running on port 5000');
});

The cookie is recieved in the response however is not set in the browser and when I log the request.cookies an empty object is printed.

enter image description here

Upvotes: 0

Views: 753

Answers (2)

MD10
MD10

Reputation: 1521

had to include { withCredentials: true } in the first call ->

axios.get('http://localhost:5000/check', { withCredentials: true } ).then(() => {
      axios.post('http://localhost:5000/cookie', null, { withCredentials: true });
    });

Upvotes: 0

Ntshembo Hlongwane
Ntshembo Hlongwane

Reputation: 1051

Firstly you will need the following packages

npm i express-session connect-mongodb-session or yarn add express-session connect-mongodb-session

Now that we have packages that we need to setup our mongoStore and express-session middleware:

//Code in server.js/index.js (Depending on your server entry point)
import expressSession from "express-session";
import MongoDBStore from "connect-mongodb-session";
import cors from "cors";
const mongoStore = MongoDBStore(expressSession);

const store = new mongoStore({
  collection: "userSessions",
  uri: process.env.mongoURI,
  expires: 1000,
});
app.use(
  expressSession({
    name: "SESS_NAME",
    secret: "SESS_SECRET",
    store: store,
    saveUninitialized: false,
    resave: false,
    cookie: {
      sameSite: false,
      secure: process.env.NODE_ENV === "production",
      maxAge: 1000,
      httpOnly: true,
    },
  })
);

Now the session middleware is ready but now you have to setup cors to accept your ReactApp so to pass down the cookie and have it set in there by server

//Still you index.js/server.js (Server entry point)

app.use(
  cors({
    origin: "http://localhost:3000",
    methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
    credentials: true,
  })
);

Now our middlewares are all setup now lets look at your login route

router.post('/api/login', (req, res)=>{
    //Do all your logic and now below is how you would send down the cooki

    //Note that "user" is the retrieved user when you were validating in logic
    // So now you want to add user info to cookie so to validate in future
    const sessionUser = {
       id: user._id,
       username: user.username,
       email: user.email,
    };
    //Saving the info req session and this will automatically save in your     mongoDB as configured up in sever.js(Server entry point)
    request.session.user = sessionUser;

    //Now we send down the session cookie to client
    response.send(request.session.sessionID);

})

Now our server is ready but now we have to fix how we make request in client so that this flow can work 100%:

Code below: React App/ whatever fron-tend that your using where you handling logging in

//So you will have all your form logic and validation and below
//You will have a function that will send request to server 

const login = () => {
    const data = new FormData();
    data.append("username", username);
    data.append("password", password);

    axios.post("http://localhost:5000/api/user-login", data, {
      withCredentials: true, // Now this is was the missing piece in the client side 
    });
};

Now with all this you have now server sessions cookies as httpOnly

Upvotes: 1

Related Questions