Framework-agnostic authentication middleware for Express and Fastify, built for Tzylo Auth CE.
- 🔐 JWT authentication
- ⚡ Express & Fastify adapters
- 🧩 Fully typed
req.auth/request.auth - 🧱 Designed for SDK and platform usage
npm install @tzylo/auth-middleware jsonwebtokenInstall the framework you use (peer dependency):
npm install express
# or
npm install fastify| Framework | Version |
|---|---|
| Express | ^4, ^5 |
| Fastify | ^5 |
import express from "express";
import {
authMiddleware,
roleMiddleware
} from "@tzylo/auth-middleware";
const app = express();
app.use(
authMiddleware({
jwtSecret: process.env.JWT_SECRET!
})
);
app.get("/protected", (req, res) => {
res.json({
authId: req.auth?.authId
});
});
app.get(
"/admin",
roleMiddleware("admin"),
(req, res) => {
res.send("Welcome Admin");
}
);
app.listen(3000, () => {
console.log("Server running on port 3000");
});import Fastify from "fastify";
import {
fastifyAuth,
fastifyRole
} from "@tzylo/auth-middleware";
const app = Fastify();
app.addHook(
"preHandler",
fastifyAuth({
jwtSecret: process.env.JWT_SECRET!
})
);
app.get("/protected", async (request) => {
return {
authId: request.auth?.authId
};
});
app.get(
"/admin",
{
preHandler: fastifyRole("admin")
},
async () => {
return "Welcome Admin";
}
);
app.listen({ port: 3000 });roleMiddleware("admin")
roleMiddleware(["admin", "moderator"])fastifyRole("admin")
fastifyRole(["admin", "moderator"])Requests without required roles will be rejected with 403 Forbidden.
After successful authentication, a user object is attached to the request.
export interface AuthUser {
id: string;
email?: string;
role?: string;
isVerified?: boolean;
}| Framework | Property |
|---|---|
| Express | req.auth |
| Fastify | request.auth |
The user object is fully typed via TypeScript module augmentation.
Express authentication middleware.
authMiddleware({
jwtSecret: string;
})Fastify authentication hook.
fastifyAuth({
jwtSecret: string;
})Express role-based authorization middleware.
roleMiddleware("admin")
roleMiddleware(["admin", "moderator"])Fastify role-based authorization hook.
fastifyRole("admin")
fastifyRole(["admin", "moderator"])- Zero
any - No manual casting
- Auto-typed request user
- Works out-of-the-box
- Frameworks as peer dependencies
- Core auth logic is framework-agnostic
- Thin adapters for each framework
- Stable public API (no deep imports)
This middleware is part of the Tzylo Auth CE ecosystem.
Planned components:
- Auth service
- SDKs
- Middleware
- Monitoring & messaging
MIT © Tzylo
Issues and pull requests are welcome. This project is evolving as part of Tzylo.