Next.js Discord

Discord Forum

Using middleware for subdomain and &:routes protection

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
I am trying to use middleware for my subdomain and its routes protection.

export async function middleware(req: NextRequest) {
    const url = req.nextUrl.clone();
    if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return;

    const host = req.headers.get('host');
    const subdomain = getValidSubdomain(host);
    if (subdomain) {
        url.pathname = `/${ subdomain }${ url.pathname }`;
        const userIsAuthenticated = false;

        if (!userIsAuthenticated) {
            const signinUrl = new URL('/auth/login', req.url);
            return NextResponse.redirect(url + `/auth/login`);
        }
    }

    return NextResponse.rewrite(url);
}

export const config = {
    // Matcher to apply the middleware to all routes
    // Adjust this matcher according to your needs
    matcher: "/(.*)",
};


Currently, the userIsAuthenticated is false, so it redirects to /auth/login. The problem is that since this is a subdomain page, it doesn't find it, because I havent rewritten the url. How to make it work? I hope you understand what this is.
imo it needs to do both, rewrite and redirect but I don't know how to make it work.

0 Replies