Search code examples
reactjsnext.jscookies

Why I am not able to get token from cookies?


When User login,app send request to backend / nextjs. Next js set cookies via res.Header(...) and then send respond back to front-end. And there I am not able to get cookies-token, but this token I can see in application/Cookies.

here is backend code


try {

  const email = req.body.email
  const password = req.body.password
  
  const user = await User.findOne({ email })

  if(!user) {
    throw new Error(`User doesn't exist!`)
  }

  // compare password
  const validPassword = await bcrypt.compare(password, user.password)
  if(!validPassword) {
    throw new Error('Invalid password!')
  }

  const signData = {
    userId: user._id,
    name: user.name,
    email: user.email,
    admin: user.isAdmin
  }
 
  const token = jwt.sign( signData, process.env.JWT_SECRET, {
      expiresIn: '4h',
    });

    res.setHeader('Set-Cookie', `token=${token}; HttpOnly; Max-Age=${60 * 60 * 24 * 1}; Path=/login`);

    return res.status(201).json({
      success: true,
      message: 'Welcome back',
    });


    
  } catch (error) {
     console.log(error)
     res.status(500).send({
      success: false,
      message: error.message
     })
  }

and here is front-end

import Cookies from 'js-cookie';

try {
      
      const res = await axios.post('/api/user/login', data, config)
      console.log(res.data)
      
      toast.success(res.data.message)

      const token = Cookies.get('token');
      console.log('token', token);  // token undefined

    } catch (error) {
      console.log(error)
      toast.error(error.response.data.message)
    }

 }

Solution

  • It's simple. the httponly cookies are not accessible in the client javascript. and that is completely expected. httponly has been created this way to prevent XSS attacks.

    Mozilla says:

    A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it's only sent to the server. For example, cookies that persist in server-side sessions don't need to be available to JavaScript and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.