0
i upgraded to apollo 4 and i am using koa js. But there are some problems with context. Authentication process does not work. Authentication time I get an error like this:
**"message": "Cannot read properties of undefined (reading ‘headers’)"
"code": "INTERNAL_SERVER_ERROR",
@[email protected][email protected]/node_modules/@apollo/server/dist/esm/utils/schemaInstrumentation.js:36:28)
backend/graphql/resolvers/posts.js:31:20
backend/util/check-auth.js:5:36**
import { ApolloServer } from "@apollo/server";
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import corsKoa from "@koa/cors";
import graphqlUploadKoa from 'graphql-upload/graphqlUploadKoa.mjs';
import { koaMiddleware as apolloServerKoa } from "@as-integrations/koa";
import http from "http";
import Koa from "koa";
import bodyParserKoa from "koa-bodyparser";
const app = new Koa();
import typeDefs from "./graphql/typeDefs.js"
import resolvers from "./graphql/resolvers/index.js"
const httpServer = http.createServer(app.callback());
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({ req }),
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
app.use(corsKoa());
app.use(
graphqlUploadKoa({
maxFileSize: 10000000, // 10 MB
maxFiles: 20,
})
);
app.use(bodyParserKoa());
app.use(apolloServerKoa(server));
httpServer.listen(process.env.PORT, () => {
console.info(
`Serving https://localhost:${process.env.PORT} for ${process.env.NODE_ENV}.`
);
});
Check-auth file:
import { GraphQLError } from "graphql"
import jwt from "jsonwebtoken"
export default (context) => {
const authHeader = context.req.headers.authorization;
if(authHeader) {
const token = authHeader.split("Bearer ")[1];
if(token) {
try {
const user = jwt.verify(token, process.env.SECRET_KEY);
return user
} catch(err) {
throw new GraphQLError('Invalid/Expired token');
}
}
throw new Error("Authentication token must be 'Bearer [token]");
}
throw new Error('Authorization header must be provided');
}
Solving the error I encountered in the backend I wrote with apollo server 4
New contributor
|