I am following this guide to make my apollo server run with Netlify functions. It works fine for non authenticated requests, but I have problems when I need to read the headers.
The guide says that I can get the req
from the express
object as shown in this snippet.
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ event, context, express }) => ({
headers: event.headers,
functionName: context.functionName,
event,
context,
expressRequest: express.req,
}),
});
However, when I try this myself, I get an undefined express
.
This is my code.
const { ApolloServer } = require("apollo-server-lambda");
const accountsGraphQL = require("./accounts.js");
const schema = require("./schema/index.js");
const server = new ApolloServer({
schema,
context: async ({ event, context, express }) => {
console.log(express); // outputs undefined
return {
headers: event.headers,
functionName: context.functionName,
event,
context: await accountsGraphQL.context(express.req), // errors `Context creation failed: Cannot read property 'req' of undefined`
}
},
introspection: true,
playground: true,
});
const handler = server.createHandler();
module.exports = { handler };
Anyway, I solved my problem by making another object that contains the req
with the headers
and authorization
.
const { ApolloServer } = require("apollo-server-lambda");
const accountsGraphQL = require("./accounts.js");
const schema = require("./schema/index.js");
const server = new ApolloServer({
schema,
context: async ({ event }) => {
return await accountsGraphQL.context({
req: { headers: { authorization: event.headers.authorization } },
});
},
introspection: true,
playground: true,
});
const handler = server.createHandler();
module.exports = { handler };