You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextAuth适配多租户SaaS自定义域名:动态Cookie域名实现咨询

解决Next.js多租户SaaS中NextAuth动态Cookie域名问题

核心思路

NextAuth支持将Cookie的domain配置为函数,通过请求上下文获取当前访问的域名,动态生成符合要求的Cookie根域名,替代硬编码的.mysaas.com。

实现步骤

1. 编写域名提取工具函数

该函数从请求的Host头中解析出可用于Cookie的根域名,兼容平台子域名和客户自定义域名:

// 可放在utils/nextauth-helpers.js或直接在[...nextauth].js中定义
function getCookieDomain(req) {
  const host = req.headers.host;
  if (!host) return undefined;

  const domainParts = host.split('.');
  // 基础逻辑:提取最后两段作为根域名(如customer.mysaas.com → .mysaas.com)
  // 如需处理.co.uk/.com.au这类特殊顶级域名,可引入psl库解析公共后缀
  if (domainParts.length >= 2) {
    return `.${domainParts.slice(-2).join('.')}`;
  }
  // 本地开发/单域名场景直接返回原host
  return host;
}

2. 修改NextAuth配置

在pages/api/auth/[...nextauth].js中,将Cookie的domain设置为动态函数:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

// 引入或直接定义上面的getCookieDomain函数

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // 这里替换为你的用户验证逻辑
        const user = { id: "1", name: "Test User", email: credentials.email };
        return user;
      }
    })
  ],
  cookies: {
    sessionToken: {
      name: `__Secure-next-auth.session-token`,
      domain: (context) => getCookieDomain(context.req),
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      path: "/"
    },
    csrfToken: {
      name: `__Host-next-auth.csrf-token`,
      domain: (context) => getCookieDomain(context.req),
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      path: "/"
    }
    // 其他Cookie(如callbackUrl、pkceCodeVerifier)也需同步设置domain
  },
  session: {
    strategy: "jwt"
  },
  // 其他NextAuth配置(如pages、callbacks等)
});

关键注意事项

  • HTTPS要求:生产环境必须使用HTTPS,否则Secure属性的Cookie无法生效,自定义域名需配置SSL证书(可使用泛域名证书或多域名证书)。
  • 特殊顶级域名处理:如果需要支持.co.uk这类公共后缀域名,可安装psl包,修改工具函数为:
    import psl from "psl";
    function getCookieDomain(req) {
      const host = req.headers.host;
      if (!host) return undefined;
      const parsed = psl.parse(host);
      return parsed.domain ? `.${parsed.domain}` : host;
    }
    
  • 本地测试:在hosts文件中添加自定义域名映射(如127.0.0.1 app.mycustomdomain.com),启动Next.js后访问该域名测试登录。
  • CNAME配置验证:确保客户的自定义域名已正确CNAME到你的SaaS主域名,且服务器已配置对应的域名解析。

内容的提问来源于stack exchange,提问作者asanas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:02:45