跳到内容

NuxtAuth 中的路径逻辑

本页面旨在阐明 @sidebase/nuxt-auth 中的路径逻辑是如何工作的。 您可以在issue commentauthjs 提供商local 提供商的 spec 文件中找到关于 URL 如何处理的完整概述。

baseURL 是一个前缀

它会在发起调用之前被添加到路径的前面。例如,

ts
export default defineNuxtConfig({
  auth: {
    baseURL: 'https://example.com/api/auth',

    provider: {
      type: 'local',
      endpoints: {
        // The call would be made to `https://example.com/api/auth/login`
        signIn: { path: '/login', method: 'post' },
      }
    }
  }
})

如果 endpoints 中提供了完整的 URL,则使用该 URL

如果您为 endpoints 提供了一个完整的 URL,则在调用端点时将使用该 URL

ts
export default defineNuxtConfig({
  auth: {
    baseURL: 'https://your.website/api',

    provider: {
      type: 'local',
      endpoints: {
        // This will call `https://example.com/user`
        getSession: { path: 'https://example.com/user' },

        // This will call `https://your.website/api/login`
        signIn: { path: '/login', method: 'post' },
      },
    }
  }
})

runtimeConfig

baseURL 的值始终位于 runtimeConfig.public.auth.baseURL。在撰写本文时,您无法直接更改它,但您可以在应用程序中读取该值

ts
const runtimeConfig = useRuntimeConfig()
const baseURL = runtimeConfig.public.auth.baseURL

此值通常是真理来源。它在 插件中设置,以便在客户端也可用。

更改 baseURL

阅读下文以了解如何更改它。

1. 环境变量

您可以通过环境变量多种方式更改 baseURL

  • 使用 NUXT_PUBLIC_AUTH_BASE_URL
  • 如果未设置 originEnvKey,则使用 AUTH_ORIGIN
  • 使用 originEnvKey 中设置的环境变量名称

环境变量应在构建时和运行时都有效。

2. baseURL

如果您没有设置环境变量,NuxtAuth 将在 nuxt.config.ts 中查找 auth.baseURL

请注意,此变量始终是静态的,仅在运行时设置,并且仍然可以在运行时使用环境变量覆盖。

不设置 baseURL 将默认为 /api/auth

3. 仅限 authjs:从传入的 HTTP 请求自动确定来源

当服务器在开发模式下运行时,NuxtAuth 可以从传入的请求自动推断 baseURL


我们建议以下设置来配置您的 AUTH_ORIGINbaseURL

ts
export default defineNuxtConfig({
  // ... other configuration
  auth: {
    baseUrl: 'https://my-backend.com/api/auth', 
    // This is technically not needed as it is the default, but it's here for illustrative purposes
    originEnvKey: 'AUTH_ORIGIN', 
  }
})
env
AUTH_ORIGIN="https://my-backend.com/api/auth"

根据 MIT 许可证发布。