How can I redirect to a subdomain from a server action?

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!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật