Skip to content

Step 6 - Middlewares

Course: Blogging website - chapter 6

Creating a middleware in hono is well documented - https://hono.dev/guides/middleware

To restrict a middleware to certain routes, you can use the following -

app.use('/message/*', async (c, next) => {
await next()
})

In our case, the following routes need to be protected -

app.get('/api/v1/blog/:id', (c) => {})
app.post('/api/v1/blog', (c) => {})
app.put('/api/v1/blog', (c) => {})

So we can add a top level middleware

app.use('/api/v1/blog/*', async (c, next) => {
await next()
})

Write the logic that extracts the user id and passes it over to the main route.

How to pass data from middleware to the route handler?

Using the context - https://hono.dev/api/context

How to make sure the types of `variables` that are being passed is correct?
const app = new Hono<{
Bindings: {
DATABASE_URL: string,
JWT_SECRET: string,
},
Variables : {
userId: string
}
}>();
Solution
app.use('/api/v1/blog/*', async (c, next) => {
const jwt = c.req.header('Authorization');
if (!jwt) {
c.status(401);
return c.json({ error: "unauthorized" });
}
const token = jwt.split(' ')[1];
const payload = await verify(token, c.env.JWT_SECRET);
if (!payload) {
c.status(401);
return c.json({ error: "unauthorized" });
}
c.set('userId', payload.id);
await next()
})

3. Confirm that the user is able to access authenticated routes

Section titled “3. Confirm that the user is able to access authenticated routes”
app.post('/api/v1/blog', (c) => {
console.log(c.get('userId'));
return c.text('signin route')
})

Send the Header from Postman and ensure that the user id gets logged on the server

💡 If you want, you can extract the prisma variable in a global middleware that set’s it on the context variable

app.use(”*”, (c) => {
const prisma = new PrismaClient({
datasourceUrl: c.env.DATABASE_URL,
}).$extends(withAccelerate());
c.set(”prisma”, prisma);
})

Ref https://stackoverflow.com/questions/75554786/use-cloudflare-worker-env-outside-fetch-scope