--- title: Authentication How-To description: "This guide covers implementing authentication in your Stacks application, including user registration, login, token management, and protected routes." --- # Authentication How-To This guide covers implementing authentication in your Stacks application, including user registration, login, token management, and protected routes. ## Setting Up Authentication ### Configuration Configure authentication in `config/auth.ts`: ```typescript // config/auth.ts import type { AuthConfig } from '@stacksjs/types' export default { // Default authentication guard default: 'api', // Available guards guards: { api: { driver: 'token', provider: 'users', }, }, // User providers providers: { users: { driver: 'database', table: 'users', }, }, // Field names username: 'email', password: 'password', // Token settings tokenExpiry: 30 * 24 * 60 * 60 * 1000, // 30 days defaultAbilities: ['*'], defaultTokenName: 'auth-token', // Password reset passwordReset: { expire: 60, // minutes throttle: 60, // seconds }, } satisfies AuthConfig ``` ### Database Setup Ensure your users table has the required fields: ```sql -- database/migrations/create-users-table.sql CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, password TEXT NOT NULL, name TEXT, email_verified_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ); -- Tokens table for API authentication CREATE TABLE personal_access_tokens ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, name TEXT NOT NULL, token TEXT NOT NULL UNIQUE, abilities TEXT, last_used_at DATETIME, expires_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); ``` Run migrations: ```bash buddy migrate ``` ## User Registration ### Registration Action ```typescript // app/Actions/Auth/RegisterAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { register } from '@stacksjs/auth' import { response } from '@stacksjs/router' import { schema } from '@stacksjs/validation' export default new Action({ name: 'RegisterAction', description: 'Register a new user', method: 'POST', validations: { email: { rule: schema.string().email(), message: 'Please provide a valid email address.', }, password: { rule: schema.string().min(8).max(255), message: 'Password must be at least 8 characters.', }, password_confirmation: { rule: schema.string(), message: 'Password confirmation is required.', }, name: { rule: schema.string().min(2).max(100), message: 'Name must be between 2 and 100 characters.', }, }, async handle(request: RequestInstance) { const email = request.get('email') const password = request.get('password') const passwordConfirmation = request.get('password_confirmation') const name = request.get('name') // Verify password confirmation if (password !== passwordConfirmation) { return response.badRequest('Passwords do not match.') } // Check if email already exists const existingUser = await User.where('email', email).first() if (existingUser) { return response.badRequest('Email already registered.') } // Register the user const result = await register({ email, password, name }) if (result) { return response.json({ message: 'Registration successful', token: result.token, user: { id: result.user.id, email: result.user.email, name: result.user.name, }, }, 201) } return response.error('Registration failed') }, }) ``` ### Registration Route ```typescript // routes/api.ts route.post('/register', 'Actions/Auth/RegisterAction') ``` ### Registration Form (Frontend) ```html

Create Account

@if(error())
{{ error() }}
@endif

Already have an account? Login

``` ## User Login ### Login Action ```typescript // app/Actions/Auth/LoginAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { Auth } from '@stacksjs/auth' import { response } from '@stacksjs/router' import { schema } from '@stacksjs/validation' export default new Action({ name: 'LoginAction', description: 'Login to the application', method: 'POST', validations: { email: { rule: schema.string().email(), message: 'Email must be a valid email address.', }, password: { rule: schema.string().min(1), message: 'Password is required.', }, }, async handle(request: RequestInstance) { const email = request.get('email') const password = request.get('password') const remember = request.get('remember', false) const result = await Auth.login({ email, password }) if (result) { return response.json({ token: result.token, user: { id: result.user?.id, email: result.user?.email, name: result.user?.name, }, // Extend token expiry if "remember me" expiresIn: remember ? 30 * 24 * 60 * 60 : 24 * 60 * 60, }) } return response.unauthorized('Invalid email or password') }, }) ``` ### Login Route ```typescript // routes/api.ts route.post('/login', 'Actions/Auth/LoginAction') ``` ### Login Form (Frontend) ```html

Login

@if(error())
{{ error() }}
@endif
Forgot password? Create account
``` ## Token Management ### Creating API Tokens ```typescript // app/Actions/Auth/CreateTokenAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { createToken } from '@stacksjs/auth' import { response } from '@stacksjs/router' import { schema } from '@stacksjs/validation' export default new Action({ name: 'CreateTokenAction', description: 'Create a new API token', method: 'POST', validations: { name: { rule: schema.string().min(1).max(100), message: 'Token name is required.', }, abilities: { rule: schema.array().optional(), message: 'Abilities must be an array.', }, }, async handle(request: RequestInstance) { const user = await request.user() if (!user) return response.unauthorized('Authentication required') const name = request.get('name') const abilities = request.get('abilities', ['*']) // `id` is `number | string`: Postgres returns BIGINT keys as strings. const token = await createToken(Number(user.id), name, abilities) return response.json({ token: token.plainTextToken, name: token.accessToken.name, abilities: token.accessToken.scopes, }, 201) }, }) ``` ### Listing Tokens ```typescript // app/Actions/Auth/ListTokensAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { tokens } from '@stacksjs/auth' import { response } from '@stacksjs/router' export default new Action({ name: 'ListTokensAction', description: 'List user tokens', method: 'GET', async handle(request: RequestInstance) { const user = await request.user() if (!user) return response.unauthorized('Authentication required') const userTokens = await tokens(Number(user.id)) return response.json({ tokens: userTokens.map(token => ({ id: token.id, name: token.name, abilities: token.scopes, updatedAt: token.updatedAt, createdAt: token.createdAt, })), }) }, }) ``` ### Revoking Tokens ```typescript // app/Actions/Auth/RevokeTokenAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { revokeTokenById, tokens } from '@stacksjs/auth' import { response } from '@stacksjs/router' export default new Action({ name: 'RevokeTokenAction', description: 'Revoke an API token', method: 'DELETE', async handle(request: RequestInstance) { const user = await request.user() if (!user) return response.unauthorized('Authentication required') const tokenId = Number(request.getParam('id')) // Only the caller's own tokens are candidates. const owned = (await tokens(Number(user.id))).some(token => token.id === tokenId) if (!owned) { return response.notFound('Token not found') } await revokeTokenById(tokenId) return response.json({ message: 'Token revoked' }) }, }) ``` ### Refreshing Tokens ```typescript // app/Actions/Auth/RefreshTokenAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { Auth } from '@stacksjs/auth' import { response } from '@stacksjs/router' export default new Action({ name: 'RefreshTokenAction', description: 'Refresh authentication token', method: 'POST', async handle(request: RequestInstance) { const currentToken = request.bearerToken() if (!currentToken) { return response.unauthorized('No token provided') } const result = await Auth.refreshToken(currentToken) if (result) { return response.json({ token: result.token, expiresIn: result.expiresIn, }) } return response.unauthorized('Invalid or expired token') }, }) ``` ## Protected Routes ### Using Auth Middleware ```typescript // routes/api.ts import { route } from '@stacksjs/router' // Public routes route.post('/login', 'Actions/Auth/LoginAction') route.post('/register', 'Actions/Auth/RegisterAction') route.post('/auth/refresh', 'Actions/Auth/RefreshTokenAction') // Protected routes - require authentication route.group({ middleware: 'auth' }, () => { route.get('/me', 'Actions/Auth/AuthUserAction') route.post('/logout', 'Actions/Auth/LogoutAction') // Token management route.get('/tokens', 'Actions/Auth/ListTokensAction') route.post('/token', 'Actions/Auth/CreateTokenAction') route.delete('/tokens/{id}', 'Actions/Auth/RevokeTokenAction') // User profile route.put('/profile', 'Actions/User/UpdateProfileAction') route.put('/password', 'Actions/User/ChangePasswordAction') }) ``` ### Get Authenticated User ```typescript // app/Actions/Auth/AuthUserAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { response } from '@stacksjs/router' export default new Action({ name: 'AuthUserAction', description: 'Get authenticated user', method: 'GET', async handle(request: RequestInstance) { const user = await request.user() if (!user) return response.unauthorized('Authentication required') return response.json({ // A number or a string: Postgres returns BIGINT keys as strings, so say // which one the response promises. id: Number(user.id), email: user.email, name: user.name, emailVerifiedAt: user.email_verified_at, createdAt: user.created_at, }) }, }) ``` `request.user()` is typed from your own User model: every column it declares (`name`, `email_verified_at`, anything you add) is typed as the model declares it, with no cast. A field the model does not declare is `unknown`, so reading one that does not exist is caught instead of quietly returning `undefined`. If the User model enables `traits.billable`, the billable methods (`user.checkout()`, `user.newSubscription()`, ...) are typed too; to use them where the trait may be off, ask first with `isBillable(user)` from `@stacksjs/orm`. ### Logout Action ```typescript // app/Actions/Auth/LogoutAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { Auth } from '@stacksjs/auth' import { response } from '@stacksjs/router' export default new Action({ name: 'LogoutAction', description: 'Logout the user', method: 'POST', async handle(request: RequestInstance) { const token = request.bearerToken() if (token) { await Auth.revokeToken(token) } return response.json({ message: 'Logged out successfully' }) }, }) ``` ## Frontend Authentication Helper Create a reusable auth service: Stacks already ships one. `useAuth()` is auto-imported in stx templates and handles login, registration, the current user and the token - see `storage/framework/defaults/functions/auth.ts` for what it does. Reach for it before writing your own. If you do need your own, this is the shape. Reactivity comes from `@stacksjs/stx`, not from a `reactivity` package - there is no such package, and a plain TypeScript module has to import what it uses even though a template would not: ```typescript // resources/functions/auth.ts import { ref } from '@stacksjs/stx' interface User { id: number email: string name: string } export const user = ref(null) export const token = ref(localStorage.getItem('token')) export const isAuthenticated = ref(!!localStorage.getItem('token')) export async function login(email: string, password: string) { const res = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }) if (!res.ok) { const error = await res.json() throw new Error(error.message || 'Login failed') } const data = await res.json() auth.token = data.token auth.user = data.user auth.isAuthenticated = true localStorage.setItem('token', data.token) return data } export async function logout() { if (auth.token) { await fetch('/api/logout', { method: 'POST', headers: { 'Authorization': `Bearer ${auth.token}`, }, }) } auth.token = null auth.user = null auth.isAuthenticated = false localStorage.removeItem('token') } export async function fetchUser() { if (!auth.token) return null const res = await fetch('/api/me', { headers: { 'Authorization': `Bearer ${auth.token}`, }, }) if (res.ok) { auth.user = await res.json() return auth.user } // Token invalid, clear auth state await logout() return null } export function getAuthHeaders() { return auth.token ? { 'Authorization': `Bearer ${auth.token}` } : {} } ``` ## Password Reset ### Request Password Reset ```typescript // app/Actions/Password/SendPasswordResetEmailAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { response } from '@stacksjs/router' import { schema } from '@stacksjs/validation' export default new Action({ name: 'SendPasswordResetEmailAction', description: 'Send password reset email', method: 'POST', validations: { email: { rule: schema.string().email(), message: 'Valid email is required.', }, }, async handle(request: RequestInstance) { const email = request.get('email') // Always return success to prevent email enumeration const user = await User.where('email', email).first() if (user) { // Generate reset token const token = await user.createPasswordResetToken() // Send email (using your email service) await sendEmail({ to: email, subject: 'Reset Your Password', template: 'password-reset', data: { resetUrl: `${APP_URL}/reset-password?token=${token}`, }, }) } return response.json({ message: 'If an account exists, a reset link has been sent.', }) }, }) ``` ### Reset Password ```typescript // app/Actions/Password/PasswordResetAction.ts import type { RequestInstance } from '@stacksjs/types' import { Action } from '@stacksjs/actions' import { hashMake } from '@stacksjs/security' import { response } from '@stacksjs/router' import { schema } from '@stacksjs/validation' export default new Action({ name: 'PasswordResetAction', description: 'Reset user password', method: 'POST', validations: { token: { rule: schema.string(), message: 'Reset token is required.', }, password: { rule: schema.string().min(8), message: 'Password must be at least 8 characters.', }, password_confirmation: { rule: schema.string(), message: 'Password confirmation is required.', }, }, async handle(request: RequestInstance) { const token = request.get('token') const password = request.get('password') const passwordConfirmation = request.get('password_confirmation') if (password !== passwordConfirmation) { return response.badRequest('Passwords do not match.') } // Verify token and get user const resetRecord = await PasswordReset.where('token', token) .where('expires_at', '>', new Date()) .first() if (!resetRecord) { return response.badRequest('Invalid or expired reset token.') } const user = await User.find(resetRecord.user_id) if (!user) { return response.badRequest('User not found.') } // Update password await user.update({ password: await hashMake(password), }) // Delete used token await resetRecord.delete() return response.json({ message: 'Password reset successfully.', }) }, }) ``` ## Next Steps - [Build an API](/bootcamp/api) - Create API endpoints - [Testing How-To](/bootcamp/how-to/testing) - Test your authentication - [Deployment How-To](/bootcamp/how-to/deploy) - Deploy with authentication ## Related Documentation - [Authentication Guide](/guide/auth) - [Auth Package](/packages/auth) - [Middleware Guide](/basics/middleware)