In this guide, we’re going to set up our backend so that it can reject unauthenticated requests from our frontend.

PropelAuth provides backend libraries for languages like Node, Python, and Rust. We then also provide more specific libraries for frameworks like Express (node), FastAPI (python), Flask (python), etc.

Choose your framework

  • Express

  • Node

  • Flask

  • FastAPI

  • Django

  • Python

  • Axum

  • Actix

  • Rust

  • Go

Installation

In your Express app, install the @propelauth/express library.

$ npm install --save @propelauth/express

Initialize

initAuth performs a one-time initialization of the library. It will verify that your apiKey is correct and fetch the metadata needed to verify requests sent from the frontend.

We recommend calling this in a new file and exporting the result.

// propelauth.js
const propelAuth = require("@propelauth/express");
module.exports = propelAuth.initAuth({
  // If true, error messages returned to the user will be detailed.
  // It's useful for debugging, but a good idea to turn off in production.
  debugMode: true,
  // You can find your Auth URL and API key under the Backend Integration
  //   section for your project at https://app.propelauth.com.
  authUrl: "https://auth.yourdomain.com",
  apiKey: "YOUR_API_KEY",
});

Protecting an API Route

This route can only be accessed from valid users:

const auth = require("./propelauth");

// requireUser is a middleware which validates the access token
app.get("/api/whoami", auth.requireUser, (req, res) => {
  res.text("Hello user with ID " + req.user.userId);
});

requireUser will return a 401 Unauthorized for requests made without a valid access token. Requests with a valid token will have req.user set with the user’s information. The full schema is available in our reference.

You can instead use optionalUser, if you want the request to proceed in either case, with req.user set only if a valid access token was provided.

How does this work?

The backend is expecting an access token to be passed in an Authorization header, like:

Authorization: Bearer YOUR_ACCESS_TOKEN

If it doesn’t find it or if the token is invalid, the request is rejected.

A Note on Latency

Verifying access tokens can be done without making a request to PropelAuth. This means that checking the auth information adds virtually no latency to your requests.

Testing our API

We can test that our API cannot be accessed by just anyone, with cURL:

# Use 3001 or whichever port the backend is running on
curl -v localhost:3001/api/whoami
...
< HTTP/2 401
...

However, in order to test that valid users do work, let’s go back and update our frontend to make the request for us.