Overview
Protect routes with JWT authentication and role-based access control.
Features
- JWT verification
- Role-based access control
- Token extraction
- Error handling
Installation
npx hanma add hono-jwt --framework hono
Dependencies
hono
Code
import { jwt } from "hono/jwt";
import { createMiddleware } from "hono/factory";
import type { Context, Next } from "hono";
const JWT_SECRET = process.env.JWT_SECRET || "it-is-so-secret";
/**
* Standard JWT Middleware
*/
export const jwtMiddleware = jwt({
secret: JWT_SECRET,
});
/**
* Role-Based Access Control (RBAC) Middleware
*/
export const checkRole = (roles: string[]) => {
return createMiddleware(async (c: Context, next: Next) => {
const payload = c.get("jwtPayload");
if (!payload || !payload.role || !roles.includes(payload.role)) {
return c.json({
success: false,
message: "Forbidden: Insufficient permissions",
}, 403);
}
await next();
});
};
/**
* Usage in app:
*
* app.use("/api/protected/*", jwtMiddleware);
* app.get("/api/admin", checkRole(["admin"]), (c) => c.text("Admin only"));
*/
Usage
import { jwtMiddleware, requireRole } from './middleware/jwt';
app.use('/api/*', jwtMiddleware);
app.get('/admin', requireRole('admin'), handler);
Dependencies
hono
Frequently Asked Questions
How do I install JWT Authentication?
Run the following command:
npx hanma add hono-jwt --framework honoWhat dependencies are required?
This snippet requires: hono. 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/middleware/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.