Mazino
Mazino

Reputation: 356

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

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.

Upvotes: 7

Views: 16157

Answers (3)

Victor Orlyk
Victor Orlyk

Reputation: 1843

if you have placed your cookies and want to read them you can get them in getServerSideProps ctx.req.cookies here your cookies

here is the link so you shouldn't try getting cookies in getStaticProps https://github.com/vercel/next.js/discussions/11734#discussioncomment-3993

Upvotes: 0

francis
francis

Reputation: 4515

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.

Upvotes: 6

yakovify
yakovify

Reputation: 130

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

Upvotes: 9

Related Questions