I'm looking to restrict access to my GraphQL API to authenticated users only. I've been using Apollo GraphQL Studio to test my API, and I've successfully set the auth token in the header. However, I'm unsure of how to retrieve and use this token in my serverless function with Next.js and Vercel.
https://i.sstatic.net/C1TWo.png
Serverless function on Vercel
export default async function handler(req: VercelRequest, res: VercelResponse) {
console.debug(req.headers);
console.debug(req.headers.authorization)
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Origin',
'https://studio.apollographql.com'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
if (req.method === 'OPTIONS') {
res.end();
return false;
}
await startLocalServer;
await apolloServerLocal.createHandler({
path: '/api/graphql',
})(req, res);
}
}
export const apolloServerLocal = new ApolloServer({
schema: schema,
introspection: true,
});
export const startLocalServer = apolloServerLocal.start();
Output
{
host: 'localhost:3000',
connection: 'keep-alive',
accept: '*/*',
'access-control-request-method': 'POST',
'access-control-request-headers': 'authorization,content-type',
origin: 'https://studio.apollographql.com',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'cross-site',
'sec-fetch-dest': 'empty',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7'
}
undefined