3

I've set up an API with a create user and an auth route. The auth route should set an httpOnly cookie containing a JWT, and should send JSON for the client to store in localhost.

In the front-end I'm doing a simple fetch.

The server responds 200 and with the JSON I expect, but somehow, the cookie doesn't get set.

However, in Postman, the cookie does indeed get set.

Express server

const express = require('express')
const cors = require('cors')

// boilerplate stuff

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

app.post('auth', (req, res) => {
  // fetch user from db, validation, bla bla bla

  const token = jwt.sign({ issuer: user.id }, keys.private, { algorithm: 'RS256' })

  res.cookie('token', token, { httpOnly: true })
  res.json(user)
})

Next.js front-end

const handleSubmit = async (e) => {
  e.preventDefault()
  try {
    const res = await fetch('http://localhost:5000/api/v1/auth', {
      method: 'post',
      mode: 'cors',
      credentials: 'include',
      headers: {
        'content-type': 'application/json',
        'accept': 'application/json',
      },
      body: JSON.stringify(formState),
    })
    const data = await res.json()
    console.log(data)
  } catch (err) {
    console.error(err)
    setError(err.message)
  }
}
8
  • did you check if SET_COOKIE header was coming in response. Also try using "credentials: 'same-origin' Commented Sep 3, 2019 at 22:12
  • Yes, it's not in the responsen headers. And I tried that. No dice 😪 Commented Sep 4, 2019 at 6:04
  • but you do get cookie set header in postman.. also i see that app.use(cors({ origin: 'localhost:3000' here port number is different than actual 5000 you use in calls. Commented Sep 4, 2019 at 6:27
  • Yes because the client is running on 3000. That's how it's supposed to be used, right? Commented Sep 4, 2019 at 6:35
  • match the ports. use same in cors statement. Also dost postman show the set header response. Commented Sep 4, 2019 at 6:45

1 Answer 1

3

'Twas resolved.

I was looking in Session Storage as opposed to Cookies in my devtools.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.