@cubicecho/graphql-better-auth
v1.2.0
Published
better-auth's endpoints as a GraphQL schema extension: typed SDL and resolvers, generated from the auth instance.
Maintainers
Readme
@cubicecho/graphql-better-auth
better-auth's endpoints as a GraphQL schema extension. Hand it an auth instance and it gives back typed SDL and resolvers, so clients sign in, read the session and manage accounts through the GraphQL API they already use.
Every auth.api endpoint a client may call becomes a query or a mutation. Arguments, result types and models come from
the instance itself, with the fields your config adds, so a new better-auth plugin brings its endpoints along. OAuth
callbacks and other redirect targets stay on HTTP.
Install
npm install @cubicecho/graphql-better-auth better-auth graphqlNode 22 or later, ESM only. better-auth 1.7 or later, graphql 16 or 17.
Quick start
Save this as quick-start.mjs and run node quick-start.mjs. Keep baseURL in your own config: without it, better-auth refuses a
sign-in from a browser, because a GraphQL request doesn't tell it its address.
import { applyBetterAuthGraphQL, betterAuthGraphQL } from '@cubicecho/graphql-better-auth';
import { betterAuth } from 'better-auth';
import { memoryAdapter } from 'better-auth/adapters/memory';
import { bearer } from 'better-auth/plugins';
import { buildSchema, graphql } from 'graphql';
const auth = betterAuth({
baseURL: 'http://localhost:3000',
secret: 'replace-this-with-a-long-random-secret',
database: memoryAdapter({ user: [], session: [], account: [], verification: [] }),
emailAndPassword: { enabled: true },
plugins: [bearer()],
});
const built = betterAuthGraphQL(auth, {
// Where better-auth finds the session: a cookie or a bearer token.
headers: (context) => context.headers,
include: ['signUpEmail', 'signInEmail', 'getSession', 'signOut'],
});
// Your own schema, with the auth fields added.
const schema = applyBetterAuthGraphQL(buildSchema('type Query { ping: Boolean }'), built);
const signUp = await graphql({
schema,
source: `mutation {
signUpEmail(name: "Ada", email: "[email protected]", password: "correct horse battery") { token }
}`,
contextValue: { headers: new Headers() },
});
const session = await graphql({
schema,
source: '{ getSession { user { name email } session { expiresAt } } }',
contextValue: { headers: new Headers({ authorization: `Bearer ${signUp.data.signUpEmail.token}` }) },
});
console.log(JSON.stringify(session.data, null, 2));Before you go live, read Security: better-auth's rate limits and router-wide CSRF check don't run on GraphQL calls, so they are yours to add.
Documentation
- Install and wire it up, on graphql-js or a schema-first server
- Operations and types: what is served, and what stays on HTTP
- Choose and change operations
- Sessions: bearer tokens and cookies
- Errors
- Patched results
- Security: what the host must check
- Common mistakes
- Every export, as
llms.txt - Changelog
