Overview
Add JWT authentication to your Elysia app.
Features
- JWT sign/verify
- Role-based access
- Token validation
- Environment config
Installation
npx hanma add elysia-jwt --framework elysia
Dependencies
@elysiajs/jwt
Code
import type { Elysia } from "elysia";
import { jwt } from "@elysiajs/jwt";
export interface JWTPayload {
id: string;
email: string;
role?: string;
[key: string]: any;
}
/**
* JWT configuration for Elysia
*/
export const setupJwt = <T extends Elysia>(app: T) => {
return app.use(
jwt({
name: "jwt",
secret: process.env.JWT_SECRET || "change-this-secret-in-production",
exp: process.env.JWT_EXPIRES_IN || "7d",
})
);
};
/**
* JWT authentication guard middleware
* Verifies JWT token from Authorization header
*/
export const authenticateJWT = async (context: any) => {
const authHeader = context.request.headers.get("authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
context.set.status = 401;
return {
success: false,
message: "Missing or invalid authorization header",
};
}
const token = authHeader.substring(7);
try {
const payload = await context.jwt.verify(token);
if (!payload) {
context.set.status = 401;
return {
success: false,
message: "Invalid or expired token",
};
}
// Attach user to context
context.user = payload;
} catch (error) {
context.set.status = 401;
return {
success: false,
message: "Token verification failed",
};
}
};
/**
* Role-based access control guard
*/
export const authorizeRole = (allowedRoles: string[]) => {
return async (context: any) => {
if (!context.user) {
context.set.status = 401;
return {
success: false,
message: "Authentication required",
};
}
const userRole = context.user.role;
if (!userRole || !allowedRoles.includes(userRole)) {
context.set.status = 403;
return {
success: false,
message: "Insufficient permissions",
required: allowedRoles,
};
}
};
};
/* USAGE:
import { Elysia } from "elysia";
import { setupJwt, authenticateJWT, authorizeRole } from "./plugins/jwt";
const app = new Elysia()
.use(setupJwt)
.post("/login", async ({ jwt }) => {
// Authenticate user...
const token = await jwt.sign({
id: "user-id",
email: "user@example.com",
role: "admin",
});
return { token };
})
.get("/protected", authenticateJWT, ({ user }) => {
return { message: "Protected route", user };
})
.get("/admin", authenticateJWT, authorizeRole(["admin"]), () => {
return { message: "Admin only" };
});
*/
Usage
import { setupJwt, authenticateJWT } from './plugins/jwt';
app.use(setupJwt);
Dependencies
@elysiajs/jwt
Frequently Asked Questions
How do I install JWT Plugin?
Run the following command:
npx hanma add elysia-jwt --framework elysiaWhat dependencies are required?
This snippet requires: @elysiajs/jwt. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
src/plugins/jwt.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.