A secure and type-safe JWT authentication plugin for Elysia applications.
Elysia JWT Plugin provides robust JSON Web Token authentication capabilities for Elysia applications, leveraging the industry-standard jose
library to ensure secure JWT handling with modern cryptographic standards and full TypeScript support.
bun add @nowarajs/elysia-jwt @nowarajs/error elysia
import { Elysia } from 'elysia';
import { jwt } from '@nowarajs/elysia-jwt';
const app = new Elysia()
.use(jwt({
secret: process.env.JWT_SECRET!,
exp: '1h' // Global expiration for all tokens
}))
.post('/login', ({ jwt }) => {
// Sign a JWT token with global expiration (1h)
return jwt.sign({ userId: 123, role: 'user' });
})
.get('/protected', async ({ jwt, headers }) => {
// Verify JWT token
const token = headers.authorization?.replace('Bearer ', '');
const payload = await jwt.verify(token);
if (!payload)
throw new Error('Invalid token');
return { user: payload };
})
.listen(3000);
import { Elysia } from 'elysia';
import { jwt } from '@nowarajs/elysia-jwt';
const app = new Elysia()
.use(jwt({
secret: process.env.JWT_SECRET!,
exp: '15m' // Default expiration
}))
.post('/login', ({ jwt }) => {
// Access token with short expiration
const accessToken = jwt.sign({
userId: 123,
role: 'user',
type: 'access'
}, { exp: '15m' });
// Refresh token with long expiration
const refreshToken = jwt.sign({
userId: 123,
type: 'refresh'
}, { exp: '7d' });
return { accessToken, refreshToken };
})
.post('/refresh', async ({ jwt, body }) => {
// Verify refresh token
const payload = await jwt.verify(body.refreshToken);
if (!payload || payload.type !== 'refresh')
throw new Error('Invalid refresh token');
// Generate new access token
const newAccessToken = jwt.sign({
userId: payload.userId,
role: 'user',
type: 'access'
}, { exp: '15m' });
return { accessToken: newAccessToken };
})
.get('/protected', async ({ jwt, headers }) => {
const token = headers.authorization?.replace('Bearer ', '');
const payload = await jwt.verify(token);
if (!payload || payload.type !== 'access')
throw new Error('Invalid access token');
return { user: payload };
});
You can find the complete API reference documentation for Elysia JWT Plugin
at:
Distributed under the MIT License. See LICENSE for more information.