skip to Main Content

I have a mono repo project working with NX. All is working fine, but I tried to add a middleware and it isn’t being caught in the requests.
I tried to put it in all different places and with _ in the name as well, but no luck.
Does anyone know what could be wrong here?
Here is an image of my project and the middleware distribution.
I’m using Nextjs 14.0.4

enter image description here

This is the code of my middleware:

import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';

export default function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;
  console.log('MIDDELWAREEEE');
  const publicPaths = ['/login', '/register'];

  if (publicPaths.includes(pathname)) {
    return NextResponse.next();
  }

  const token = request.cookies.get('auth_token');
  console.log('token', token);
  if (!token) {
    return redirectToLogin(request);
  }

  if (!token.value) {
    return redirectToLogin(request);
  }
}

function redirectToLogin(req: NextRequest) {
  const url = req.nextUrl.clone();
  url.pathname = '/login';
  return NextResponse.redirect(url);
}

2

Answers


  1. Chosen as BEST ANSWER

    So after some days, I could reach the solution. I hope it helps someone in the future.

    In next.config.js, if you altered the page extensions, like I did, to:

    pageExtensions: ['page.tsx', 'api.ts'],
    

    I had to add an entry to cover page.ts:

    pageExtensions: ['page.tsx','page.ts', 'api.ts'],
    

    Finally added the middleware as middleware.page.ts, at pages level, and it started working.

    In sum, the middleware must match the pageExtensions defined on next.config.js


  2. The middleware file must be at the same level as pages folder, also no need to do default export.

    you can check this official docs provided by nextjs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search