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
...
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,
},
}
}