mirror of
https://github.com/better-auth/better-auth.git
synced 2026-06-02 04:16:38 -05:00
0d4ce489c8b29ad9b7cccdcfaf86b6bbc8a4b66c
Better Auth
The Authentication Library for Javascript.
Installation
pnpm install better-auth
Usage
Start by create a folder called auth in your project somewhere.
Create two files
server.tsandclient.tsin the auth folder.
In the
server.tsfile, create a betterAuth instance.See the example below.
import { betterAuth } from 'better-auth';
import { prismaAdapter } from "better-auth/adapters/prisma-adapter"
import { github } from "better-auth/providers"
export const auth = betterAuth({
//database adapter
adapter: prismaAdapter(prisma),
//auth providers
providers: [github({
clientId: "",
clientSecret: ""
})],
/**
* better auth requires you to define a user schema.
* The only field assumed to be present is the id
* field.
*/
user: {
fields: {
email: {
type: "string"
},
emailVerified: {
type: "boolean"
},
name: {
type: "string"
},
image: {
type: "string"
}
}
}
})
Now you need to mount the handler on your application.
Next JS
app/api/[...auth]/routes.ts
import { handler } from "@/lib/auth/server";
import { toNextJSHandler } from "better-auth/next";
export const { GET, POST } = toNextJSHandler(handler);
SvelteKit
src/hooks.server.ts
import { auth } from "$lib/auth/server";
import { svelteKitHandler } from "better-auth/svelte-kit";
export async function handle({ event, resolve }) {
return svelteKitHandler({ auth, event, resolve });
}
- In the
client.tsfile, create a client betterAuth instance. See the example below.
Make sure to import the
authinstance from theserver.tsfile as a type and pass it to thecreateAuthClientfunction. That will be used to infer from your auth config on the server.
import { createAuthClient } from "better-auth/client"
import type { auth } from "./server"
export const client = createAuthClient<typeof auth>()({
baseURL: "http://localhost:3000" //the base url of the server
})
- Now you can use the client instance to authenticate users in your client side code. See the example below.
import { client } from "@lib/auth/client"
const loginWithGithub = async () => {
const user = await client.signInOrSignUp({
provider: "github",
//this data will be used to create a user if the user does not exist
data: {
email: "email" //this is mapping the field to the response from the provider
name: "name",
image: "avatar_url",
emailVerified: {
value: true //you can pass a static value like this
}
},
callbackUrl: "http://localhost:3000/dashboard" //the url to redirect to after authentication. This is optional.
})
}
Description
Releases
112
Languages
TypeScript
99.4%
CSS
0.3%
MDX
0.2%