Next.js Discord

Discord Forum

How to chain middlewares

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
I want to use middleware to make subdomains work, as well as protect my routes. I want to use middleware chaining, but currently it doesn't work.

//middleware.ts 
import { NextResponse } from "next/server";
import { withSubDomain } from "./middlewares/withSubDomain";
import { withAuth } from "@/middlewares/withAuth";
export function defaultMiddleware() {
    return NextResponse.next();
}
export default withSubDomain(withAuth(defaultMiddleware));

// withAuth.js
import type { NextMiddleware, NextRequest, NextFetchEvent } from 'next/server';
import { NextResponse } from 'next/server';
import { MiddlewareFactory } from "@/middleware/types";

export const withAuth: MiddlewareFactory = (next: NextMiddleware) => {
    return async (req: NextRequest, event: NextFetchEvent) => {

        console.log("withAuth");
        const token = req.headers.get('token');
        const userIsAuthenticated = false; // Replace with your authentication logic

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

        return next(req, event);
    };
};

// withSubDomain.js
import type { NextMiddleware, NextRequest } from 'next/server';
import { NextFetchEvent, NextResponse } from 'next/server';
import { getValidSubdomain } from '@/utils/Subdomain';
import { MiddlewareFactory } from "@/middleware/types";
export const withSubDomain: MiddlewareFactory = (next: NextMiddleware) => {
    return async (req: NextRequest, event: NextFetchEvent) => {
        const url = req.nextUrl.clone();
        const host = req.headers.get('host');
        const subdomain = getValidSubdomain(host);
        if (subdomain) {
            // Subdomain available, rewriting
            url.pathname = `/${subdomain}${url.pathname}`;
            return NextResponse.rewrite(url); // Return the rewritten response
        }

        return next(req, event); 
    };
};

0 Replies