Apollo Client with httpOnly (nextjs)

I’m using Apollo Client to make authentificated request with graphQL, but I want to store my cookie in httpOnly so it’s more secure, but I getit easily in my Apollo Client

//Apollo Client (wrap with provider on all my app)

const defaultOptions = {
    watchQuery: {
      fetchPolicy: "no-cache",
      errorPolicy: "ignore",
    },
    query: {
      fetchPolicy: "no-cache",
      errorPolicy: "all",
    },
  };

  const httpLink = createHttpLink({
    uri: API_URL,
  });

 
  const authLink = setContext((_, { headers }) => {
    // This work only with httpOnly = false
    const token = Cookies.get('token')
   
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : "",
      }
    }
  });
  
  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
    defaultOptions: defaultOptions
  });

  export default client

This is how I setup my cookie on user login/register :sweat_smile:

...
if (res.ok) {
      // Set Cookie
      res.setHeader(
        'Set-Cookie',
        cookie.serialize('token', data.jwt, {
          httpOnly: true,
          secure: process.env.NODE_ENV !== 'development',
          maxAge: 60 * 60 * 24 * 7, // 1 week
          sameSite: 'strict',
          path: '/',
        })
      )
...

In all my other page, I can get my cookie like this :

//example with a classique get request
//helper cookie
function parseCookies(req) {
  return cookie.parse(req ? req.headers.cookie || '' : '')
}
export async function getServerSideProps({ req }) {
  const { token } = parseCookies(req)

  const res = await fetch(`${API_URL}/events/me`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })

  const events = await res.json()

  return {
    props: {
      events,
      token,
    },
  }
}

@Kaherdin what is Cookies in your example - a custom object or something from a 3rd party library? If custom can you share the code, or if a 3rd party library can you post which one?

I’m using js-cookie for client and jshttp-cookie for server

Your cookie is set as httpOnly: true meaning you can’t read it with JavaScript. It will be sent along with your HTTP requests and can only be modified on the server.