skip to Main Content

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.

2

Answers


  1. 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'
        }
    }
    
    Login or Signup to reply.
  2. maybe you need to change
    "/subapp/play" to "/play" and also "/subapp/api/:path*" to "/api/:path*"

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