How Next.js 13 middleware is used as error handling?

My Next is currently used as a back-end framework, and the middleware only processes related api files. Now I have implemented the function of uniformly detecting apiKey, but I also want to add an error capture function for all apis. How to achieve it?
4 Replies
francis.miko
francis.miko15mo ago
Here is my existing code
export function middleware(request: Request) {
try {
const apiKey = request.headers.get("API_KEY");
if (apiKey !== env.API_KEY) {
return new Response(JSON.stringify({ error: "Invalid API key" }), {
status: 401,
});
}
return NextResponse.next();
} catch (err) {
if (error instanceof z.ZodError) {
return new Response(JSON.stringify(error.issues), { status: 422 });
}

return new Response(JSON.stringify(error), { status: 500 });
}
}
export function middleware(request: Request) {
try {
const apiKey = request.headers.get("API_KEY");
if (apiKey !== env.API_KEY) {
return new Response(JSON.stringify({ error: "Invalid API key" }), {
status: 401,
});
}
return NextResponse.next();
} catch (err) {
if (error instanceof z.ZodError) {
return new Response(JSON.stringify(error.issues), { status: 422 });
}

return new Response(JSON.stringify(error), { status: 500 });
}
}
But this doesn't work, I can't catch related errors thrown by my api, for example my POST api:
const inputSchema = z.object({
message: z.string(),
});

export async function POST(req: Request) {
const body = await req.json();
const input = inputSchema.parse(body); // (input invalid parmas) => throws ZodError

return new Response(JSON.stringify({ status: "ok" }));
}
const inputSchema = z.object({
message: z.string(),
});

export async function POST(req: Request) {
const body = await req.json();
const input = inputSchema.parse(body); // (input invalid parmas) => throws ZodError

return new Response(JSON.stringify({ status: "ok" }));
}
I don't want to add a try catch module to each of my api codes. Doing so would defeat my original intention of using middleware to catch errors. So do you guys have any good insights? blessjmg
RockBacon
RockBacon15mo ago
Middleware works perfectly to check apiKeys because it runs before your api function. It wouldn't work well to catch errors because it only runs once before your api function. Where I think you have gone wrong is you think you run the api from the middleware file, like calling a function. Unfortunately that's not correct from what I see in the docs, the function prepares another http request which is sent to the api function. On the other hand middleware on vercel is run on a completely different instance to where your api function is run. I may be wrong, I am new to this stuff as well😀
NotRoman
NotRoman15mo ago
Correct, the middleware has no way of knowing if the api has an error. Middleware acts as a door, once the request is past the door it can’t see anything else
francis.miko
francis.miko15mo ago
Want results from more Discord servers?
Add your server