Discord

获取你的 Discord 凭证

要使用 Discord 登录,你需要一个客户端 ID 和客户端密钥。你可以从 Discord 开发者门户 获取它们。

请确保在本地开发时将重定向 URL 设置为 http://localhost:3000/api/auth/callback/discord。在生产环境中,应将其设置为你的应用的 URL。如果你更改了身份验证路由的基础路径,也应相应地更新重定向 URL。

配置提供程序

要配置提供程序,你需要导入该提供程序并将其传递给身份验证实例的 socialProviders 选项。

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({ 
    socialProviders: {
        discord: { 
            clientId: process.env.DISCORD_CLIENT_ID as string, 
            clientSecret: process.env.DISCORD_CLIENT_SECRET as string, 
        }, 
    },
})

用法

【Usage】

使用 Discord 登录

【Sign In with Discord】

要使用 Discord 登录,你可以使用客户端提供的 signIn.social 函数。signIn 函数接受一个包含以下属性的对象:

  • provider:要使用的提供者。应设置为 discord

【To sign in with Discord, you can use the signIn.social function provided by the client. The signIn function takes an object with the following properties:

  • provider: The provider to use. It should be set to discord.】
auth-client.ts
import { createAuthClient } from "better-auth/client"
const authClient =  createAuthClient()

const signIn = async () => {
    const data = await authClient.signIn.social({
        provider: "discord"
    })
}

选项

【Options】

有关所有社交提供商支持的完整选项列表,请查阅 提供商选项

【For the full list of options supported by all social providers, check the Provider Options.】

机器人权限(可选)

【Bot Permissions (Optional)】

如果你在使用 Discord OAuth 的 bot 权限范围时,可以使用 permissions 选项来指定机器人的权限。它可以是一个按位或的值(例如 2048 | 16384 表示发送消息和嵌入链接)或一个具体的权限值(例如 16384 表示嵌入链接)。

【If you're using the bot scope with Discord OAuth, you can specify bot permissions using the permissions option. It can either be a bitwise value (e.g 2048 | 16384 for Send Messages and Embed Links) or a specific permission value (e.g 16384 for Embed Links).】

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({ 
    socialProviders: {
        discord: {
            clientId: process.env.DISCORD_CLIENT_ID as string,
            clientSecret: process.env.DISCORD_CLIENT_SECRET as string,
            permissions: 2048 | 16384, // Send Messages + Embed Links
        }, 
    },
})

注意: permissions 参数仅在 OAuth2 范围中包含 bot 时才有效。阅读更多关于 Discord 机器人权限 的信息。

On this page