Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
req.cookies.token is undefined in express js (MERN stack)

I am using a middleware where I have to check whether the user is authenticated or not but I am unable to get the cookie from react to express js when I already have a cookie in the front end as shown in the image below: enter image description here

Here is my express js code

require("dotenv").config();
const port = process.env.PORT || 5050;
const express = require("express");
const app = express();
const cors = require("cors");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const { authenticate } = require("/controllers/user");
const Post = require("/models/post");

// mongodb connection

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



app.get("/api/post/:slug", authenticate , async (req, res) => {
    const slug = req.params.slug;
    const post = await Post.findOne({ slug })
    res.send(post);
});

app.listen(port, () => {
    console.log("Blog server is running!!");
})

Here I have code in authenticate middleware

const authenticate = async (req, res, next)  => {
  console.log(req.cookies["token"])
  next();
}

The expected code should log the token cookie in the console. But I have undefined in the express js console like this one!

enter image description here

Let me show you the front end code below

import { useParams } from 'react-router-dom'
export default function Post() {
 const [post, setPost] = useState([]);
 const loadPost = async () => {
    const { slug } = useParams();
    const all_posts = await fetch(`http://localhost:5000/api/post/${slug}`)
    const res = await all_posts.json();
    setPost([res]);
 }
  useEffect(() => {
    loadPost();
  }, [])
  return (
    <>
     ...///
    </>
  )
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can't handle with this way, Because when we work with Express and React or any other application where the frontend & backend works separately then we store the Authentication token in local storage. Please look below example:

require("dotenv").config();
const port = process.env.PORT || 5050;
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const { authenticate } = require("/controllers/user");
const Post = require("/models/post");

// mongodb connection

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



app.get("/api/post/:slug", authenticate , async (req, res) => {
    const slug = req.params.slug;
    const post = await Post.findOne({ slug })
    res.send(post);
});

app.listen(port, () => {
    console.log("Blog server is running!!");
})

Authentication Middleware:

const jwt = require('jsonwebtoken')

module.exports = {
  authenticate: async (req, res, next) => {
    try {
      const { token } = req.headers
      if (!token) return helper.apiResponse(req, res, 'UNAUTHORIZED', true, null, 'Expected a bearer token')
      const [authType, auth] = token.trim().split(' ')
      if (authType !== 'Bearer') return helper.apiResponse(req, res, 'UNAUTHORIZED', true, null, 'Expected a bearer token')

      jwt.verify(auth, process.env.TOKEN_SECRET, function (err, decoded) {
        if (err) return helper.apiResponse(req, res, 'UNAUTHORIZED', true, null, err, true)
        if (decoded.loggedInUser) {
          req.user = decoded.loggedInUser
          next()
        } else {
          return helper.apiResponse(req, res, 'UNAUTHORIZED', true, null, 'Invalid Token')
        }
      })
    } catch (error) {
      return helper.apiResponse(req, res, 'UNAUTHORIZED', true, null, error, true)
    }
  }
}

And In Frontend(React Application) we will store the token in local storage to persist, when the user refreshes the page it will not change/remove until you removed the token yourself. React application code:

import { useParams } from 'react-router-dom'
export default function Post() {
 const [post, setPost] = useState([]);
 const token = localstorage.getItem('token')
 const loadPost = async () => {
    const { slug } = useParams();
    const all_posts = await fetch(`http://localhost:5000/api/post/${slug}`,{
    headers: new Headers({
        'token': token, 
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    })
    const res = await all_posts.json();
    setPost([res]);
 }
  useEffect(() => {
    loadPost();
  }, [])
  return (
    <>
     ...///
    </>
  )
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!