Node.js auth example

Additional resources


In this example, we show how to add authentication and access control to a basic Node.js application.

To use Userfront with a Node.js application, your backend server needs to read and verify JWT access tokens. After that, your code can determine how to respond to each request.

In this example, we have a server with 3 GET routes:

RouteDescription
/publicThis route is accessible by anyone, whether they are logged in or not. It returns public data.
/protectedThis route is accessible by any user who is logged in. It returns data specific to the user.
/adminThis route is only accessible by users with an admin role. It returns data for admins only.

We'll use Express.js for the routing, but other frameworks work in the same manner.

We cover each route below.

#Public route

No authentication or access controls are needed for the public route. Thus, the server code is straightforward:

Response:

#Protected route

To build a route that only logged-in users can view, we need the client (frontend) to include the user's JWT access token in the authorization header for the request.

Our server can then read the header and reject any requests without a valid JWT access token.

#Client (frontend)

The client should include the user's JWT access token in the authorization header of the request:

#Server (backend)

Our server route should read the authorization header for the request, then verify the JWT access token with the workspace's JWT public key before responding. We are using the open source jsonwebtoken library to verify the token.

If the JWT access token is invalid or expired, we throw an error and return Unauthorized.

Response:

#Admin route

To build a route that only admin users can view, we need the client (frontend) to include the user's JWT access token in the authorization header for the request.

Our server can then read the header and reject any JWT access tokens that don't have the admin role.

#Client (frontend)

The client should include the user's JWT access token in the authorization header of the request:

#Server (backend)

To restrict the route to admins only, we need to check that the JWT access token has the admin role.

Userfront's JWT access token look like this encoded:

And the JWT access token's payload looks like this decoded:

So we want to check that the payload.authorization[tenantId].roles array contains the admin role.

As with the protected route, our server should read the authorization header for the request, then verify the JWT access token with the workspace's JWT public key before responding. We are using the open source jsonwebtoken library to verify the token.

If the JWT access token is invalid, expired, or missing the admin role, we throw an error and return Unauthorized.

Response: