question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Api have empty cookies for SSR request

See original GitHub issue

Bug report

Describe the bug

As sad in docs:

API routes provide built in middlewares which parse the incoming request. Those middlewares are: req.cookies - An object containing the cookies sent by the request.

But any API SSR request contain no cookies ({} object).

Also you can’t set cookies for SSR request from api.

Client-side requests at the same time have cookies and and be set from api.

To Reproduce

Run simple server

// pages/user
const User = () => {
  return <div>test</div>
}

User.getInitialProps = async () => {
  const init = await fetch('http://localhost/api/user')
  return { init }
}
//pages/api/user
export default (req, res) => {
   console.log(req.cookies) // will return {} on SSR

   // will not set cookies on SSR
   res.writeHead(200, {
        'Set-Cookie': 'mycookie=test',
        'Content-Type': 'text/plain'
      })
      .end(JSON.stringify('smth'))
}

Expected behavior

  1. req.cookies should contain cookies when page was SSR.
  2. You should be able to set cookies when page was SSR.

System information

  • OS: [Windows]
  • Browser [chrome 79.0.3945.88]
  • Version of Next.js: [9.1.6]

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
rafaelalmeidatkcommented, Dec 30, 2019

fetch does send cookies by default if the origin of the requests is the same since the default option for credentials is same-origin. It doesn’t work like that when running on the server because the server itself doesn’t store the cookies of previous requests, you need to do as Tim showed and reinclude the cookies from the request headers (because the browser stores the cookies, and will attach them automatically in the headers for each request to the server).

2reactions
ZiiMakccommented, Jan 15, 2020

@ivanhueso i use custom fetch like this:

const fetchHeaders = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
  cookie: ''
}

const fetchAPI = (
  link,
  body,
  req,
  res
) => {
  return new Promise((resolve) => {
    if (req && req.headers.cookie) fetchHeaders.cookie = req.headers.cookie

    fetch(link, {
      method: 'POST',
      headers: fetchHeaders,
      credentials: 'same-origin',
      body: JSON.stringify(body)
    })
      .then(raw)=> raw.json())
      .then(parsed => {
          if (req && res) {
            // SSR
            res.setHeader('Set-Cookie', 'cookie1=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;')
          } else {
            // client
            document.cookie = 'cookie1=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
          }
        }

        resolve(parsed)
      })
      .catch((err) => {
        !isProd && console.log(err)
      })
  })
}

export { fetchAPI }
Read more comments on GitHub >

github_iconTop Results From Across the Web

Why are cookies not sent to the server via getServerSideProps ...
That's because the request inside getServerSideProps doesn't run in the browser - where cookies are automatically sent on every request ...
Read more >
Next.js — Handling Cookies in getServerSideProps
I want to fetch my userds data on the server before rendering the page, meaning Idll first need to validate the access token,...
Read more >
Client and Server Side Cookies in Next.js - YouTube
Let's learn how to set/ remove cookies both in the browser but also on the server in Next.js. This will allow us to...
Read more >
Quasar - SSR and using cookies - DEV Community ‍ ‍
When building for SSR, use only the $q.cookies form. If you need to use the import { Cookies } from 'quasar', then you'll...
Read more >
How to Use Cookies to Persist State in NextJS - Medium
make a request to sign in a user by calling a function to log the user in. We take the response from that...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found