How to get 401 from useJWT() plugin to return with 401 instead of 500 using Express #3140
-
|
Hi all. First of all, thank you for creating this awesome, awesome library. I've been digging into the useJWT(), and it looks like the plugin itself actually returns a 401: https://github.com/dotansimha/graphql-yoga/blob/main/packages/plugins/jwt/src/index.ts#L117C21-L117C21 Is there a standard best practice using Express to bubble up errors properly? I'm all for error masking but we want to be able to display an Unauthorized error on the front-end and act accordingly instead of a 500 Internal Error code which is inappropriate. Here is my example loosely based on the Express Integration docs: import express, { Application, Request, Response } from "express";
import dotenv from "dotenv";
import { createYoga, createGraphQLError } from "graphql-yoga";
import { useJWT } from "@graphql-yoga/plugin-jwt";
import helmet from "helmet";
import { pgPool } from "./lib/db/postgres";
import { createSchema } from "./lib/graphql/schema";
dotenv.config({
path: process.env.NODE_ENV === "production" ? ".env.production" : ".env.development",
});
const PORT: number = Number(process.env.NODE_PORT) ?? 15000;
const app: Application = express();
const yogaRouter = express.Router();
yogaRouter.use(
helmet({
contentSecurityPolicy: {
directives: {
"style-src": ["'self'", "unpkg.com"],
"script-src": ["'self'", "unpkg.com", "'unsafe-inline'"],
"img-src": ["'self'", "raw.githubusercontent.com"],
},
},
}),
);
app.get("/livez", (req: Request, res: Response) => {
res.status(200).send("OK");
});
app.get("/readyz", (req: Request, res: Response) => {
res.status(200).send("OK");
});
export async function init() {
try {
const schema = await createSchema();
const yoga = createYoga({
schema,
cors: {
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
},
plugins: [
useJWT({
issuer: process.env.AUTH_ISSUER ?? "",
jwksUri: `${process.env.AUTH_ISSUER}/oauth/v2/keys`,
}),
],
});
yogaRouter.use(yoga);
app.use(yoga.graphqlEndpoint, yogaRouter);
app.use(helmet());
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server started on http://0.0.0.0:${PORT}/`);
});
return app;
} catch (err) {
console.error(`Failed to start the server`, err);
}
}
init().catch((err) => console.error(err)); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
Actually, it should already bubble up. The error thrown contains an |
Beta Was this translation helpful? Give feedback.
Actually, it should already bubble up. The error thrown contains an
http.codeextension that should set the status code on the response, this is a Yoga feature. If it's not bubbling up, it is probably a bug :-) Can you open an issue with a simple reproduction on Stackblitz for example ?