0

I'm building a Next.js app using Strapi as a CMS and authentication server. I've managed to get a JWT from the auth endpoint, and have stored it in a cookie. To retrieve secured content from strapi I need to send this JWT in the header

I'm using Apollo to send graphQL queries to strapi, according to their documentation, I can easily set auth headers by adding this to utils/apollo.js

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = cookies.get('jwt') <-- This is what I'd like to do, but I can't figure out how to access cookies at this point.
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

How can I access cookies in the app mentioned above. It's not part of a component, though it is used to build a HOC?

While using localstorage is an option, I've read that cookies are a safer way to store data. Using cookies with secure isn't an option - I'm not sure if strapi allows it, and also because there are multiple frontend origins vercel builds previews for all branches

1 Answers1

2

Once you set the cookie it will be passed in the Cookie header so you need to retrieve it from there, not the cookies object which is only available in the browser but not available in server-side requests. In addition, if you're using CORS you will need to enable credentials both in the client and server, specifically in the client you need to set credentials: 'include'. This is required setting for cookies to work.

Yos
  • 1,182
  • 12
  • 29