// functions/api/_middleware.ts
export const onRequest: PagesFunction<Env> = async ({ next, request, env }) => {
try {
// if options method called
if (request.method.toLowerCase() === "options") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, PATCH, DELETE, OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
}
// response
const response = await next();
// set headers
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Headers", "*");
response.headers.set("Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE, OPTIONS");
response.headers.set("Access-Control-Max-Age", "86400");
// If request from /authenticate route pass next()
if (request.url.endsWith("/api/authenticate")) return response;
// Get token
const token = request.headers.get("Authorization").split(" ")[1];
// Verify jwt token
const data = await jwtVerify(token, new TextEncoder().encode(env.JWT));
return response;
} catch (error) {
return new Response(JSON.stringify({ message: (error as Error).message }), {
status: 500,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, PATCH, DELETE, OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
}
};