Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS middleware function is not triggered in zone

I have an application reachable via the following http://localhost (this is the url of the main application) and another one reachable via http://localhost/subapp (this is the url of a sub-application), I am using nginx and docker to run both apps in two different containers on the same port (3000).

The subapplication is a subzone and I am having troubles setting up a middleware function to check if the user is authenticated, preventing the user to reach certain pages if it is not authenticated.

To achieve this I have an authentication system (build with next-auth) in the main application (running on http://localhost).

In the subapplication I have checked that the cookie is correctly set when the user is authenticated and it is not set when the user access the page without being authenticated, however the middleware function is not getting called for some reason.

Below is the implementation of the middleware function in the subapp (running on http://localhost/subapp):

export { default } from "next-auth/middleware";
import { NextRequest, NextResponse } from 'next/server';

export async function middleware(req: NextRequest, res: NextResponse) {
    console.log("TEST"); // this is never printed
    const session = req.cookies.get('next-auth.session-token');
    if(session)
        return NextResponse.next();
    else
        return NextResponse.redirect(new URL('/signin', req.url)); // this should send the user back to http://localhost/sign-in in case the user is not authenticated
}

export const config = {
    matcher: [
        "/",
        "/subapp/play",
        "/subapp/api/:path*",
    ],
    pages: {
        signIn: '/signin'
    }
}

I have also tried using the middleware function of the main app (running on http://localhost) to prevent the user to reach the protected pages but it is not working.

like image 709
DRE Avatar asked Oct 17 '25 06:10

DRE


2 Answers

When you set basePath: '/subapp', in next.config.js your matcher in middleware.js is "/play" not "/subapp/play". If you include subapp in your matcher the middleware will never be called.

So try:

export const config = {
    matcher: [
        "/",
        "/play",
        "/api/:path*",
    ],
    pages: {
        signIn: '/signin'
    }
}
like image 96
evandwight Avatar answered Oct 20 '25 14:10

evandwight


maybe you need to change "/subapp/play" to "/play" and also "/subapp/api/:path*" to "/api/:path*"

like image 23
mohammad mohammadi nodhe Avatar answered Oct 20 '25 13:10

mohammad mohammadi nodhe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!