supastarter for Next.jsAPI
Protect API endpoints
Learn how to protect your API endpoints in your supastarter application.
Check if the user is authenticated
To protect your API endpoints, you can use the authMiddleware
in your router or on a specific endpoint.
We'll use the posts example from the Define an API endpoint guide and make it only available for authenticated users.
The middlware will throw an error if the user is not authenticated.
The authMiddleware
will also provide the session
and user
infromation to the endpoint. If the handler is reached, both objects are available in the context.
Admin-only endpoints
There is a second middleware which does the same as the authMiddleware
, but it also checks if the user has the admin
role.