简体   繁体   中英

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.

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'
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM