How to add header or request param to getServerSideProps in Nextjs

Viewed 2063

I want to pass a simple string value or a JWT access token to the getServerSideProps function in NextJS, then I want to do some requests for the user from the server side. My JWT access token is currently stored in memory (in a state).

How do I pass my JWT access token or any other string value to getServerSideProps?

I have read many times that you can pass cookies to getServerSideProps but I wanted to add this access token value to the request header or request param.

Is there any other way than cookies or querystring parameter to add custom values to the getServerSideProps function in nextjs that is executed on the server?

1 Answers

You can pass values to getServerSideProps if you set up a custom server. You can use their example to parse the url and then add values to the query, but note that their example uses URL.parse from node and that has been deprecated so you'll want to modify it for more recent versions of node.

A second way to handle this (still using a custom server) would be to take advantage of Express-style response locals. Using their first example on the above-linked Next page, it could look like this:

// Custom Server
...
app.prepare().then(() => {
  createServer((req, res) => {
    res.locals.myServerValue = "someValue"
    handle(req, res)
  }).listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
...

Now in getServerSideProps, you can access this value from the response object:

export const getServerSideProps = async ({ res }) => {
  // Get the value from res.locals
  const myServerValue = res.locals.myServerValue

  // Do something with myServerValue
  console.log(myServerValue) // prints "someValue"

  // If desired, pass the value to the page if that's how you're using it
  return {
    props: {
      myServerValue
    }
  }
}
Related