Protected routes
Learn how to protect your API routes.
Hono has built-in support for middlewares, which are functions that can be used to modify the context or execute code before or after a route handler is executed.
That's how we can secure our API endpoints from unauthorized access. Below are some examples of you can leverage middlewares to protect your API routes.
Authenticated access
After validating the user's authentication status, we store their data in the context using Hono's built-in context. This allows us to access the user's information in subsequent middleware and procedures without having to re-validate the session.
Here's an example of middleware that validates whether the user is currently logged in and stores their data in the context:
Then we can use our defined middleware to protect endpoints by adding it before the route handler:
Feature-based access
When developing your API you may want to restrict access to certain features based on the user's current subscription plan. (e.g. only users with "Pro" plan can access teams).
You can achieve this by creating a middleware that will check if the user has access to the feature and then pass the execution to the next middleware or procedure:
Use it within your procedure the same way as we did with enforceUserIsAuthed
middleware:
These are just examples of what you can achieve with Hono middlewares. You can use them to add any kind of logic to your API (e.g. logging, caching, etc.)
Last updated on