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

SvelteKit+Auth.js预览模式报TypeError: basePath?.replace不是函数

问题概述

开发SvelteKit应用时使用了处于实验阶段的@auth/sveltekit,运行npm run preview时触发错误,但npm run dev模式下一切正常,错误信息如下:

TypeError: basePath?.replace is not a function
    at createActionURL (file:///path/to/project/node_modules/@auth/core/lib/utils/env.js:71:45)
    at auth (file:///path/to/project/.svelte-kit/output/server/chunks/hooks.server.js:83:22)
    at event.locals.auth (file:///path/to/project/.svelte-kit/output/server/chunks/hooks.server.js:140:35)
    at load (file:///path/to/project/.svelte-kit/output/server/entries/pages/_layout.server.js:4:33)
    at load_server_data (file:///path/to/project/.svelte-kit/output/server/index.js:519:42)
    at file:///path/to/project/.svelte-kit/output/server/index.js:1997:24
相关代码
// @ts-nocheck
import { SvelteKitAuth } from "@auth/sveltekit";
import Google from "@auth/core/providers/google";
import { AUTH_SECRET, GOOGLE_ID, GOOGLE_SECRET } from "$env/static/private";
import pool from "$lib/db";

export const {handle} = SvelteKitAuth({
    providers: [
        Google({
            clientId: GOOGLE_ID,
            clientSecret: GOOGLE_SECRET
        })
    ],
    callbacks: {
        async signIn({profile}) {
            const emailDomain = profile?.email?.split('@')[1];
            if(emailDomain !== "customDomain") {
                console.log('Unauthorised Domain', profile?.email)
                throw new AccessDenied('Unauthorised_Domain')
            }

            const [rows] = await pool.query('SELECT * FROM users WHERE email = ?', [profile?.email])

       
            if(rows.length === 0){
                await pool.query('INSERT INTO users (name, email, picture) VALUES (?, ?, ?)', [
                    profile?.name,
                    profile?.email,
                    profile?.picture
                ]);
            }
            return true;
        },
        async redirect({baseUrl }) {
            return baseUrl;  // Redirect to the home page after sign-in
        },
    secret: AUTH_SECRET
}})
问题细节
  • 错误发生在@auth/core的createActionURL函数中,具体是调用basePath.replace的行
  • 仅在npm run preview模式下触发,开发模式无此问题
  • 使用SvelteKit结合Auth.js配置了Google认证
  • 预览模式下basePath疑似未定义或类型错误,但开发模式能正常获取
环境配置
  • SvelteKit版本:2.0.0
  • @auth/core:0.32.0
  • @auth/sveltekit:1.2.0
疑问
  1. 如何解决预览模式下的basePath?.replace is not a function错误?
  2. 预览环境中导致basePath未定义或传递错误的原因是什么?
已尝试方案
  • 硬编码basePath为/,无效
  • 检查.env文件中的环境变量配置,确认无误
  • 问题仅在预览模式下持续存在

解决方案

1. 显式指定basePath和baseUrl参数

在SvelteKitAuth配置中手动传入这两个参数,避免预览模式下自动获取失败:

import { dev } from '$app/environment';

export const {handle} = SvelteKitAuth({
    // 保留原有配置
    basePath: "/auth", // Auth.js默认路由前缀,需与实际路由一致
    baseUrl: dev ? "http://localhost:5173" : "http://localhost:4173", // 开发/预览环境地址
    // ... 其余配置
})

2. 升级@auth相关依赖

SvelteKit 2.0.0属于较新版本,可能与旧版@auth/sveltekit存在兼容性问题,尝试升级到最新兼容版本:

npm update @auth/sveltekit @auth/core

升级后重新构建并启动预览:

npm run build && npm run preview

3. 同步SvelteKit的base路径配置

如果svelte.config.js中配置了paths.base,需确保@auth/sveltekit能正确读取该值:

// svelte.config.js
import adapter from '@sveltejs/adapter-auto';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  kit: {
    adapter: adapter(),
    paths: {
      base: '/your-custom-base' // 若有自定义base路径需填写
    }
  }
};

export default config;

然后在SvelteKitAuth中引入该路径:

import { kit } from '$svelte.config.js'; // 需确保svelte.config.js支持导出

export const {handle} = SvelteKitAuth({
    basePath: `${kit.paths.base}/auth`,
    // ... 其余配置
})

4. 排查环境变量传递问题

预览模式下确认环境变量是否正确加载,可在hooks.server.js中临时打印验证:

console.log("Preview env:", process.env.AUTH_URL, process.env.NODE_ENV);

若变量缺失,启动预览时显式传递环境变量:

env $(cat .env) npm run preview

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:55:01