débutant
débutant

Reputation: 31

How to access httpOnly cookies in Next.js?

Can anyone suggest what would be the best way to access tokens from httpOnly cookies?

I'm using Next.js 12.x.x as the front end (http://localhost:3000).

My API server runs separately (http://localhost:4000).

Once login, the API server returns the JWT token. I am storing tokens in cookies - httpOnly. I am using Apollo client and hooks like useQuery.

What I know is:

  1. httpOnly can't be read from the client side with JavaScript.
  2. If I make a request to Next.js API, from the request, I can read the cookies and get the token.
export default async function (req, res) { 
  const { cookies } = req;
  const jwt = cookies.token;
}
  1. I can access the token from getServerSideProps
export async function getServerSideProps(context) {
    const jwt = context.req.cookies.token;
        
}

BUT,

  1. I'm using an Apollo client.
  2. I want to use useQuery hooks.
  3. My API needs token info to return responses, which are running separately.
  4. I can NOT use hooks in getServerSideProps.

I need to pass Authorization in the header. Can anyone help me to understand the best and most secure way to get the token and add in the header of apolloClient? I want to avoid creating APIs at frontend (Next.js).

_app.js look like below.

import { useEffect } from "react";
import { ApolloProvider, ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

export  function MyApp({Component, pageProps} ) {

  const httpLink = createHttpLink({
    uri: 'http://localhost:4000/graphql',
  });
  
  const authLink = setContext((_, { headers }) => {
    const token = "HOW TO FIND YOU ?????";
    return {
      headers: {
        ...headers,
        Authorization: `Bearer ${token}`
      }
    }
  });
  
  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
  });

  return (
    <ApolloProvider client={client}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </ApolloProvider>
  );
}
export default MyApp;

Upvotes: 3

Views: 11671

Answers (1)

Mooder
Mooder

Reputation: 41

Best way is using proxy with api routes and pass the auth token to header on every request.

Read this article to understand more

Upvotes: 0

Related Questions