Reputation: 31
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:
export default async function (req, res) {
const { cookies } = req;
const jwt = cookies.token;
}
getServerSideProps
export async function getServerSideProps(context) {
const jwt = context.req.cookies.token;
}
BUT,
useQuery
hooks.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