GraphQL Context Argument

Learn how to use the context argument to share things like database connections, dataloaders, and more across requests.

Jamie Barton

Published on 13 Dec 2021 by Jamie Barton

Notes

const resolvers = {
Query: {
me: (parent, args, context, info) => {
return context.secretValue;
},
},
};
app.use(
"/graphql",
graphqlHTTP((req) => {
const { authorization } = req.headers;
if (!authorization) {
throw new Error("Unauthorized");
}
const secretValue = secrets[authorization];
return {
schema,
graphiql: {
headerEditorEnabled: true,
},
context: {
secretValue,
startTime: Date.now(),
},
extensions: ({ context }) => ({
runTime: Date.now() - context.startTime,
}),
};
})
);