1

My application assigns refreshToken to the reponse object as following:

newRefreshToken, { httpOnly: true, secure: true, sameSite: 'None', maxAge: 24 * 60 * 60 * 1000 });

And when I check the Postman I see the assigned JWT token there like below:

jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InFAcS5jb20iLCJpYXQiOjE2NTQ4MDMxMzIsImV4cCI6MTY2MjU3OTEzMn0.ustL6WVKWog53jAe8IFlaLw9g4BL7F1LJg5qc94F4TI; Path=/; Secure; HttpOnly; Expires=Fri, 10 Jun 2022 19:32:11 GMT;

But when I try to read the cookies using req.cookies I get this result after printing out the req object:

  cookies: [Object: null prototype] {},
  signedCookies: [Object: null prototype] {},

This is my server.js file content:

require('dotenv').config();
const express = require('express');
const app = express();
var passport = require('passport');
const path = require('path');
const cors = require('cors');
const corsOptions = require('./config/corsOptions');
const { logger } = require('./middleware/logEvents');
const errorHandler = require('./middleware/errorHandler');
const verifyJWT = require('./middleware/verifyJWT');
const cookieParser = require('cookie-parser');
const credentials = require('./middleware/credentials');
const mongoose = require('mongoose');
const connectDB = require('./config/dbConn');
const PORT = process.env.PORT || 3000;

// initializing passport
app.use(passport.initialize());

// Connect to MongoDB
connectDB();

// custom middleware logger
app.use(logger);

// Handle options credentials check - before CORS!
// and fetch cookies credentials requirement
app.use(credentials);

// Cross Origin Resource Sharing
app.use(cors(corsOptions));

// built-in middleware to handle urlencoded form data
app.use(express.urlencoded({ extended: false }));

// built-in middleware for json 
app.use(express.json());

//middleware for cookies
app.use(cookieParser());

//serve static files
app.use('/', express.static(path.join(__dirname, '/public')));

// routes
app.use('/', require('./routes/root'));
app.use('/register', require('./routes/register'));
app.use('/auth', require('./routes/auth'));
app.use('/refresh', require('./routes/refresh'));
app.use('/logout', require('./routes/logout'));

app.use(verifyJWT);
app.use('/employees', require('./routes/api/employees'));
app.use('/users', require('./routes/api/users'));

app.all('*', (req, res) => {
    res.status(404);
    if (req.accepts('html')) {
        res.sendFile(path.join(__dirname, 'views', '404.html'));
    } else if (req.accepts('json')) {
        res.json({ "error": "404 Not Found" });
    } else {
        res.type('txt').send("404 Not Found");
    }
});

app.use(errorHandler);

mongoose.connection.once('open', () => {
    console.log('Connected to MongoDB');
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
});
GoodMan
  • 542
  • 6
  • 19
  • You need a cookie parser if you are not using any check this https://www.npmjs.com/package/cookie-parser – Dhruv Pal Jun 09 '22 at 20:09
  • @DhruvPal: I am using that. I added my `server.js` file in the question. Maybe I am using it in a wrong order? – GoodMan Jun 09 '22 at 20:14
  • So If I understand it right, you are assuming that postman is ending some cookies? Why don't you paste postman curl here? – Dhruv Pal Jun 09 '22 at 20:19
  • @DhruvPal: In part of code I do send refreshToken back to user like this `res.cookie('jwt', newRefreshToken, { httpOnly: true, secure: true, sameSite: 'None', maxAge: 24 * 60 * 60 * 1000 }); ` and I can see it in Postman cookies automatically, but when I try to send a request to the endpoint that fetches this cookie using `req.cookies` it seems it doesn't work and can't see the cookies. – GoodMan Jun 09 '22 at 20:31
  • @DhruvPal I don't know how to paste Postman curl. – GoodMan Jun 09 '22 at 20:32
  • Your client-side code seems to be right, just cross-check [this](https://stackoverflow.com/questions/56481547/cookie-displayed-in-node-console-with-postman-not-with-browser) and [this](https://stackoverflow.com/questions/70318918/set-cookies-are-present-in-postman-but-not-in-axios), if that helps – Dhruv Pal Jun 10 '22 at 09:41
  • @DhruvPal: Thanks for your help, but what is Axios? I don't use it on my code. – GoodMan Jun 10 '22 at 19:04

1 Answers1

1

If you are in development i.e If you are working on localhost, try setting secure: true to secure: false when you are setting cookies in

res.cookie('jwt', newRefreshToken, { 
  httpOnly: true, 
  secure: false, //changes secure
  sameSite: 'None', 
  maxAge: 24 * 60 * 60 * 1000 
});

source problem : https://github.com/expressjs/express/issues/4924

answerer by dnrahmath

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
dnrahmath
  • 11
  • 2