Search code examples
javascriptnode.jsexpresscookies

POST/GET request with Credentials not sending cookies


First of all, I know there is many duplicates of this question but I have tried them all and it doesn't work. Hence I am starting a new one.

apart from axios I also tried using fetch with the same results

backend server

  • "express": "^4.18.2",
  • "cors": "^2.8.5",

    const express = require("express");
    const cors = require("cors");
    const jwt = require("jsonwebtoken")
    const cookieParser = require('cookie-parser')
    require("dotenv").config();
    
    const allowedOrigins = [
        'http://127.0.0.1:5173',
        'http://localhost:5173',
    ];
    
    const headers = (req, res, next) => {
        const origin = req.headers.origin;
        if (allowedOrigins.includes(origin)) {
            res.setHeader('Access-Control-Allow-Origin', origin)
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST')
            res.setHeader('Access-Control-Allow-Credentials', true);
        }
        next();
    }
    
    const corsOptions = {
        origin: allowedOrigins,
        credentials: true,
        optionsSuccessStatus: 200
    }
    
    app.use(headers);
    app.use(cors(corsOptions))
    app.use(express.json())
    app.use(cookieParser())
    
    app.post("/foo", (req,res) => {
        const token = jwt.sign(
            { 'foo': "qwerty" },
            process.env.JWT_SECRET,
            { expiresIn: '1d' }
        )
        res.cookie(
            'jwt',
            token,
            { httpOnly: true, secure: true, sameSite: 'None', maxAge: 24 * 60 * 60 * 1000 }
        );
    }
    
    app.get("/bar", (req,res) => {
        const cookies = req.cookies
        console.log(cookies) // getting cookies undefined here no matter what i try.
        if (!cookies?.jwt) return res.sendStatus(401)
        // do something below
    }

frontend client

  • "react": "^18.2.0",
  • "axios": "^1.3.2",

    import axios from 'axios';
    
    const app = async () => {
        const instance = axios.create({
            baseURL: "http://127.0.0.1:3001",
            withCredentials: true //first way to set credentials
        })
    
        instance.defaults.withCredentials = true //second way to set credentials
    
        const foo = await instance.post("/foo")
        if (!foo.ok) return
    
    
        const response = await instance.get("/bar", {
          withCredentials: true //third way to set credentials
        }
        console.log(response) //401
    }


Solution

  • Changing api calls from 127.0.0.1 to localhost fixed the issue. But I don't know why. Hope someone can explain.