4

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 2

2

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'
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This approach makes sense, I think that is why in the official documentation this example does not exist, otherwise it's just the same behavior if you read this nextjs.org/docs/migrating/incremental-adoption#subpath
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.