I'm trying to pass a middleware variable to my API pages through "req" but it's not working
I tried to send user token to pages using the "req", but it always returns null
my middleware: pages/api/users/_middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { getAccessToken } from '@lib/auth';
declare module 'next/server' {
interface NextRequest {
token: string;
}
}
export async function middleware(req: NextRequest) {
try {
const [, token] = await getAccessToken(req.headers.get('authorization'));
req.token = token;
return NextResponse.next();
} catch(e) {
const err = e as Error;
const errorPayload = {
error: 'unauthorized',
error_message: err.message,
};
return new Response(
JSON.stringify(errorPayload),
{ status: 401 },
);
}
}
my api page that i tried to get the user token from req: pages/api/users/[userId].ts
import { NextApiRequest, NextApiResponse } from 'next';
import { UserModel } from '@database/models';
declare module 'next' {
interface NextApiRequest {
token: string;
}
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const user = await UserModel.findOne({ token: req.token });
res.status(200).send({
success: true,
user,
});