I’m working on a multi-tenant application where each tenant gets a different subdomain (e.g., “tenant1.localhost:3000″, “tenant2.localhost:3000″, etc.)
I’m using a middleware file to determine if a user is logged in, and to “rewrite” their URL from “tenant1.localhost:3000” to “localhost:3000/tenant1”.
When the user goes to their subdomain, the middleware will redirect them to a login page (the user sees “tenant1.localhost:3000/login” on their browser, but under the hood it is “localhost:3000/tenant1/login).
After a successful login (performed in a server action), the user should be redirected to “tenant1.localhost:3000/dashboard”. The browser’s address bar shows this URL, as expected. The browser’s developer tools also shows a redirect (303) to “tenant1.localhost:3000/dashboard”, which is good. However, when the next request comes into the server’s middleware in response to the redirect, the request’s header (req.headers.get('host')
) shows a host of “localhost:3000” (missing the “tenant1” subdomain).
This completely messes up the functionality of the middleware, which ends up doing an incorrect rewrite operation (use case 2). As a result, the user sees the wrong page, even though the URL in their browser is correct.
If I do a page reload on the browser, then a new request comes into the middleware with the correct host and the correct page is displayed to the user.
Does anyone know why the redirect from the “signIn” server action is resulting in a host header of “localhost:3000”?
This is how I’m doing the redirect in the “signIn” server action (hard coded the tenant for simplicity/testing):
redirect(`http://tenant1.localhost:3000/dashboard`);
Here’s my middleware file:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import verifyToken from './actions/(auth)/cognito-verifier';
const ROOT_DOMAINS = [
'localhost:3000',
process.env.NEXT_PUBLIC_ROOT_DOMAIN,
'www.' + process.env.NEXT_PUBLIC_ROOT_DOMAIN,
];
// This function can be marked `async` if using `await` inside
export async function middleware(req: NextRequest) {
console.log('middeware running');
const url = req.nextUrl;
// Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
let hostname = req.headers.get('host')!;
console.log('hostname: ', hostname);
console.log('url: ', url);
const searchParams = req.nextUrl.searchParams.toString();
const path = `${url.pathname}${searchParams.length > 0 ? `?${searchParams}` : ''}`;
// Allow main domain to go through without any modifications or authentication:
if (ROOT_DOMAINS.includes(hostname) && path === '/') {
console.log('use case-1');
return NextResponse.next();
}
// Redirect to the root if a user tries to access a sub-path of the root domain:
if (ROOT_DOMAINS.includes(hostname) && path !== '/') {
console.log('use case 2');
return NextResponse.redirect(new URL('/', req.url));
}
// Allow login to go through
if (path === '/login') {
console.log('use case 3 - login URL');
return NextResponse.rewrite(new URL(`/${hostname}${path}`, req.url));
}
console.log('start token check');
console.log('check 1');
const accessToken = req.cookies.get('accessToken')?.value;
if (!accessToken) {
return NextResponse.redirect(new URL(`/login`, req.url));
}
console.log('check 2');
const { invalidToken } = await verifyToken(accessToken);
if (invalidToken) {
return NextResponse.redirect(new URL(`/login`, req.url));
}
console.log('use case 4 - final rewrite');
const splitDomain = hostname.split('.');
console.log('splitDomain[0]: ', splitDomain[0]);
return NextResponse.rewrite(new URL(`/${splitDomain[0]}${path}`, req.nextUrl.origin));
}
// See "Matching Paths" below to learn more
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
// '/dashboard',
],
};
Thanks!