Next.js Better Auth + JWT Usage Skill
When to use this Skill
Use this Skill whenever you are:
- Setting up or modifying authentication in a Next.js 16+ App Router
project that uses Better Auth.
- Integrating the Better Auth JWT plugin to issue tokens for a
separate backend (e.g. FastAPI) to verify.
- Building login, signup, logout flows and protecting routes in the
frontend.
- Attaching auth headers (e.g.
Authorization: Bearer <token>) to
frontend → backend API calls.
This Skill must be generic enough to work for any Next.js + Better Auth
project, not just a single repository.
Core goals
- Use Better Auth as the primary auth mechanism in Next.js.
- Use the Better Auth JWT plugin (or equivalent feature) when a
separate backend needs to verify users using a shared secret or JWKS.
- Keep auth logic centralized and reusable:
- Single server-side auth instance.
- Single client-side wrapper for auth methods.
- Single place where JWT tokens are retrieved/attached to API calls.
- Protect routes and layouts in a predictable way using standard
Next.js mechanisms (middleware, server actions, layouts).
Architecture assumptions
- Frontend: Next.js 16+ App Router.
- Auth provider: Better Auth running in the same Next.js app or as a
dedicated auth server reachable via HTTP.
- Sessions: Better Auth manages sessions (cookies) by default.
- Tokens: Better Auth JWT plugin is used to issue tokens that other
services (e.g. FastAPI backend) can verify.
Do not assume a specific database or UI library. The patterns must focus
on auth, not styling or persistence.
Core components and files
The typical structure for Better Auth in Next.js includes:
Auth config / server instance (e.g. lib/auth.ts):
- Creates the Better Auth instance with secret, database config, and
plugins (including JWT).
- Provides server-side helpers to get the current session/user.
Auth route handler (e.g. app/api/auth/[...all]/route.ts):
- Mounts the Better Auth handler on a Next.js API route.
- Handles all auth-related HTTP requests (login, signup, logout, etc.).
Client-side helpers (e.g. lib/auth-client.ts):
- Expose thin, typed wrappers for login, signup, logout, etc.
- Use Better Auth client utilities to call the auth API route.
JWT retrieval:
- Use the Better Auth JWT plugin endpoints or helpers to obtain a JWT
token that encodes user identity.
- Store the token in a secure place suitable for the usage pattern
(e.g. HTTP-only cookie or server-side retrieval when calling
another backend).
Route protection:
- Use middleware, layouts, or server actions to check whether a user
is authenticated before rendering protected pages.
- Redirect unauthenticated users to the login page or a public route.
Better Auth integration rules
Create a single auth configuration module (e.g. lib/auth.ts) that:
- Calls
createAuth(...) from Better Auth with:
- A strong secret from environment variables (e.g.
BETTER_AUTH_SECRET).
- Database connection details.
- Session strategy (e.g. cookie, JWT) as needed.
- Registers the JWT plugin if tokens are required for external
services.
Mount the auth handler in an API route such as:
app/api/auth/[...all]/route.ts using Better Auth’s Next.js
handler utilities.
Do not duplicate auth configuration in multiple files.
JWT usage with Better Auth
Enable the JWT plugin in the Better Auth configuration when a
separate backend (e.g. FastAPI) needs to verify users.
Use the plugin-provided endpoints or helpers to:
- Request a JWT for the currently authenticated user.
- Optionally provide a JWKS endpoint or shared secret for backend
verification.
Keep JWT-specific logic in a dedicated module (e.g. lib/auth-jwt.ts):
- Functions to fetch or derive the JWT from the current session.
- Helpers to pass the JWT to backend API clients.
Never hard-code JWT secrets in source files; always read them from
environment variables.
Attaching JWT to backend API calls
Combine this Skill with the API client patterns Skill:
- The API client should accept a function like
getAuthToken that
retrieves the JWT from a trusted source (session, cookies, Better
Auth helper).
Rules for attaching the token:
- Use the
Authorization header with Bearer <token> format unless
the backend explicitly requires something else.
- Attach the token in one central place (e.g. inside
createApiClient
configuration), not in every component.
The backend (e.g. FastAPI) is responsible for verifying the token
using the same secret or JWKS that Better Auth uses.
Route protection and session access (frontend)
Environment variables and secrets
Always read the Better Auth secret and URLs from environment
variables, for example:
BETTER_AUTH_SECRET
BETTER_AUTH_URL or equivalent base URL for the auth handler.
Never log secrets or tokens.
Document required environment variables in the project README, not in
the Skill.
Things to avoid
- Mixing multiple unrelated auth systems in the same project without a
clear separation.
- Hard-coding JWT secrets, tokens, or auth URLs in components.
- Manually building login/signup flows that bypass Better Auth when the
library is already configured.
- Attaching tokens directly in dozens of components instead of using
a central API client configuration.
References inside the repo
When present, this Skill should align with these conventions:
@/lib/auth.ts – Better Auth server-side configuration.
@/lib/auth-client.ts – Client-side helpers for login/signup/logout.
@/lib/auth-jwt.ts – Helpers to obtain JWT tokens from Better Auth.
@/lib/api.ts – Shared API client that attaches the JWT token.
app/api/auth/[...all]/route.ts – Auth route that mounts Better Auth.
If any of these files are missing, propose creating them following
Better Auth’s official Next.js integration guides and the patterns
described above, instead of inventing a completely new auth flow.
1---2name: nextjs-better-auth-jwt-usage3description: Standard patterns for using Better Auth in Next.js 16+ App Router projects, including server and client integration, JWT plugin usage, and attaching tokens to backend API calls in a reusable way.4---5
6# Next.js Better Auth + JWT Usage Skill
7
8## When to use this Skill
9
10Use this Skill whenever you are:
11
12- Setting up or modifying authentication in a Next.js 16+ App Router
13 project that uses **Better Auth**.
14- Integrating the Better Auth **JWT plugin** to issue tokens for a
15 separate backend (e.g. FastAPI) to verify.
16- Building login, signup, logout flows and protecting routes in the
17 frontend.
18- Attaching auth headers (e.g. `Authorization: Bearer <token>`) to
19 frontend → backend API calls.
20
21This Skill must be generic enough to work for any Next.js + Better Auth
22project, not just a single repository.
23
24## Core goals
25
26- Use Better Auth as the primary auth mechanism in Next.js.
27- Use the Better Auth **JWT plugin** (or equivalent feature) when a
28 separate backend needs to verify users using a shared secret or JWKS.
29- Keep auth logic centralized and reusable:
30 - Single server-side auth instance.
31 - Single client-side wrapper for auth methods.
32 - Single place where JWT tokens are retrieved/attached to API calls.
33- Protect routes and layouts in a predictable way using standard
34 Next.js mechanisms (middleware, server actions, layouts).
35
36## Architecture assumptions
37
38- Frontend: Next.js 16+ App Router.
39- Auth provider: Better Auth running in the same Next.js app or as a
40 dedicated auth server reachable via HTTP.
41- Sessions: Better Auth manages sessions (cookies) by default.
42- Tokens: Better Auth JWT plugin is used to issue tokens that other
43 services (e.g. FastAPI backend) can verify.
44
45Do not assume a specific database or UI library. The patterns must focus
46on auth, not styling or persistence.
47
48## Core components and files
49
50The typical structure for Better Auth in Next.js includes:
51
52- **Auth config / server instance** (e.g. `lib/auth.ts`):
53 - Creates the Better Auth instance with secret, database config, and
54 plugins (including JWT).
55 - Provides server-side helpers to get the current session/user.
56
57- **Auth route handler** (e.g. `app/api/auth/[...all]/route.ts`):
58 - Mounts the Better Auth handler on a Next.js API route.
59 - Handles all auth-related HTTP requests (login, signup, logout, etc.).
60
61- **Client-side helpers** (e.g. `lib/auth-client.ts`):
62 - Expose thin, typed wrappers for login, signup, logout, etc.
63 - Use Better Auth client utilities to call the auth API route.
64
65- **JWT retrieval**:
66 - Use the Better Auth JWT plugin endpoints or helpers to obtain a JWT
67 token that encodes user identity.
68 - Store the token in a secure place suitable for the usage pattern
69 (e.g. HTTP-only cookie or server-side retrieval when calling
70 another backend).
71
72- **Route protection**:
73 - Use middleware, layouts, or server actions to check whether a user
74 is authenticated before rendering protected pages.
75 - Redirect unauthenticated users to the login page or a public route.
76
77## Better Auth integration rules
78
79- Create a single auth configuration module (e.g. `lib/auth.ts`) that:
80
81 - Calls `createAuth(...)` from Better Auth with:
82 - A strong secret from environment variables (e.g. `BETTER_AUTH_SECRET`).
83 - Database connection details.
84 - Session strategy (e.g. cookie, JWT) as needed.
85 - Registers the JWT plugin if tokens are required for external
86 services.
87
88- Mount the auth handler in an API route such as:
89
90 - `app/api/auth/[...all]/route.ts` using Better Auth’s Next.js
91 handler utilities.
92
93- Do not duplicate auth configuration in multiple files.
94
95## JWT usage with Better Auth
96
97- Enable the JWT plugin in the Better Auth configuration when a
98 separate backend (e.g. FastAPI) needs to verify users.
99
100- Use the plugin-provided endpoints or helpers to:
101 - Request a JWT for the currently authenticated user.
102 - Optionally provide a JWKS endpoint or shared secret for backend
103 verification.
104
105- Keep JWT-specific logic in a dedicated module (e.g. `lib/auth-jwt.ts`):
106
107 - Functions to fetch or derive the JWT from the current session.
108 - Helpers to pass the JWT to backend API clients.
109
110- Never hard-code JWT secrets in source files; always read them from
111 environment variables.
112
113## Attaching JWT to backend API calls
114
115- Combine this Skill with the API client patterns Skill:
116
117 - The API client should accept a function like `getAuthToken` that
118 retrieves the JWT from a trusted source (session, cookies, Better
119 Auth helper).
120
121- Rules for attaching the token:
122
123 - Use the `Authorization` header with `Bearer <token>` format unless
124 the backend explicitly requires something else.
125 - Attach the token in one central place (e.g. inside `createApiClient`
126 configuration), not in every component.
127
128- The backend (e.g. FastAPI) is responsible for verifying the token
129 using the same secret or JWKS that Better Auth uses.
130
131## Route protection and session access (frontend)
132
133- For **protected routes**:
134
135 - Use Next.js middleware or route-specific layouts to:
136 - Check whether the user is authenticated using Better Auth’s
137 session helpers.
138 - Redirect unauthenticated users to the login page.
139
140- For **server components / server actions**:
141
142 - Use Better Auth’s server-side helpers to access the current session
143 and user.
144 - Avoid exposing raw tokens to client components when not necessary.
145
146- For **client components**:
147
148 - Provide hooks or context that expose:
149 - Auth state (logged in / logged out).
150 - Basic user info (id, email, name).
151 - Actions (login, logout, signup).
152
153## Environment variables and secrets
154
155- Always read the Better Auth secret and URLs from environment
156 variables, for example:
157
158 - `BETTER_AUTH_SECRET`
159 - `BETTER_AUTH_URL` or equivalent base URL for the auth handler.
160
161- Never log secrets or tokens.
162- Document required environment variables in the project README, not in
163 the Skill.
164
165## Things to avoid
166
167- Mixing multiple unrelated auth systems in the same project without a
168 clear separation.
169- Hard-coding JWT secrets, tokens, or auth URLs in components.
170- Manually building login/signup flows that bypass Better Auth when the
171 library is already configured.
172- Attaching tokens directly in dozens of components instead of using
173 a central API client configuration.
174
175## References inside the repo
176
177When present, this Skill should align with these conventions:
178
179- `@/lib/auth.ts` – Better Auth server-side configuration.
180- `@/lib/auth-client.ts` – Client-side helpers for login/signup/logout.
181- `@/lib/auth-jwt.ts` – Helpers to obtain JWT tokens from Better Auth.
182- `@/lib/api.ts` – Shared API client that attaches the JWT token.
183- `app/api/auth/[...all]/route.ts` – Auth route that mounts Better Auth.
184
185If any of these files are missing, propose creating them following
186Better Auth’s official Next.js integration guides and the patterns
187described above, instead of inventing a completely new auth flow.