Getting Started
This guide will help you set up authentication in your Elysia.js application using elysia-auth.
Installation
bun add elysia-auth
Basic Setup
- First, create a new Elysia application and add the required environment variables:
// .env
AUTH_SECRET="your-secret-key"
AUTH_GOOGLE_ID="your-google-client-id"
AUTH_GOOGLE_SECRET="your-google-client-secret"
- Set up the authentication middleware:
import { Elysia } from 'elysia'
import { ElysiaAuth } from 'elysia-auth'
import Google from '@auth/core/providers/google'
const app = new Elysia()
.use(ElysiaAuth({
providers: [
Google({
clientId: process.env.AUTH_GOOGLE_ID,
clientSecret: process.env.AUTH_GOOGLE_SECRET
})
],
secret: process.env.AUTH_SECRET,
trustHost: true
}))
.listen(3000)
Protecting Routes
Method 1: Using authGuard
import { authGuard } from 'elysia-auth'
app
.group('/admin', app => app
.use(authGuard({
secret: process.env.AUTH_SECRET,
unauthorizedMessage: 'Please login first'
}))
.get('/dashboard', () => 'Admin Dashboard')
)
Method 2: Using protectPaths
import { protectPaths } from 'elysia-auth'
app.use(protectPaths(
['/admin', '/api/private'],
{
secret: process.env.AUTH_SECRET
}
))
Session Handling
The middleware automatically handles sessions using JWTs. You can access the session in your routes:
app.get('/profile', ({ session }) => {
if (!session.isAuthenticated) {
return 'Not logged in'
}
return `Hello ${session.user.email}`
})
Custom User Data
You can transform the auth user data:
app.use(authGuard({
getUserData: async (authUser) => ({
id: authUser.sub,
email: authUser.email,
// Add custom fields
role: await getUserRole(authUser.sub)
})
}))
Next Steps
- Learn about available Authentication Providers
- Explore Advanced Configuration
- Check out Examples