How to read cookies in getStaticProps and getStaticPaths in Next.js

Viewed 7584

I cannot read cookies in getStaticPaths and getStaticProps, in SSR, I can request the cookie with context but even with packages such as js-cookie, cookie-cutter, cookies, I am unable to read the cookies set, which makes it impossible to get the data.

Cookie

This is the token I want to get, I removed httpOnly for development.

export async function getStaticPaths(){
    const data = await callApi("/jobs", "GET", token)

    const paths = data.map(jobs => ({
        params: {slug: jobs.slug}
    }))
    return{
        paths,
        fallback: true,
    }
}

This is the getStaticPaths.

3 Answers

both getStaticPaths and getStaticProps are methods that run on the server (node.js), therefore cookies which is a browser API are not available yet

Cookies can be accessed both on the server req.cookies or req.headers.cookie and on the client document.cookie. But unlike getServerSideProps where the HTML is generated at runtime, getStaticProps generates the HTML at build time and therefore has no know knowledge of requesting devise/browser. This is evident from how user-agent looks when the request is sent from getStaticProps:

'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'

Also, there's a demo app here showing how this all works.

If your reason for trying to access cookies from getStaticProps is for authentication, have a look at this post on The way they built the zeit.co/vercel dashboard (fully static)

Also here, using next-redux-wrapper to access state from getStaticProps.

Related