I have the following Apollo setup
import { ApolloServer } from '@apollo/server';
import { handleAuth } from '../../api/helpers/AuthenticationHelpers/handleAuth';
import resolvers from '../../api/graphql/resolvers';
const typeDefs = require("../../api/graphql/schema");
const createContext = async ({ req }) => {
console.log("Handling Context");
console.log("REQUEST::::", req);
return { user: null }; // Simplify the logic for testing
};
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
playground: true,
context: createContext,
});
export { apolloServer };
That I then export and input into this file, where I start it up...
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { apolloServer } from "./server"
export default startServerAndCreateNextHandler(apolloServer);
I have also tried doing it the following way, according to Apollo Official Docs and Next/Apollo Integration Docs
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { apolloServer } from "./server"
const createContext = async ({ req }) => {
console.log("Handling Context");
console.log("REQUEST::::", req); // Add this line for debugging
if (!req || !req.headers) {
console.error("Request object or headers undefined");
return { user: null };
}
const token = req.headers.authorization;
if (!token) {
return { user: null };
}
const user = await handleAuth(token);
return user;
};
export default startServerAndCreateNextHandler(apolloServer, {context: createContext});
Both variations do not work.
I can access the API perfectly fine, I can send requests for mutations and queries so everything is working as expected except for my context function not firing. The logs are never displayed no matter what I do. When this was working, it was logging the context every 2 or so seconds. What am I doing incorrectly?
Apollo Server 4 does not have that context
option - if you are using TypeScript, you should get a warning here.
This is documented here in the docs.
Instead, you would pass the context
as an argument to e.g. expressMiddleware
or startStandaloneServer
.