Pass a variable from next.js middleware to api req

Viewed 641

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,
  });
1 Answers

You cannot do this with next.js middleware as of now. If you used express middleware, it is possible with res.locals

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

app.use((req, res, next) => {
  res.locals.path = req.path;
  next();
});

next.js middleware has no res, adding local variables directly on the request object is not supported. This is wrong:

export default async function handler(req: NextApiRequest, res: NextApiResponse) {}

next.js middleware takes req and ev

export default async function handler(req,ev) {

     console.log({req,ev})
}
Related