Skip to content

Express Backend Integration

PropelAuth offers an end-to-end managed user authentication library for seamless integration into your Express application. This guide will show you how to connect the PropelAuth library to your backend. For the full Express Library Reference, click here.

Quick example

The following example creates a route which can only be accessed from logged-in users.

const propelAuth = require("@propelauth/express");
const {requireUser} = propelAuth.initAuth({
    authUrl: "YOUR_AUTH_URL", //(1)
    apiKey: "YOUR_API_KEY", //(2)
})

// requireUser is a middleware which validates the access token
app.get("/hello", requireUser, (req, res) => {
    res.text("Hello user with ID " + req.user.userId);
})
  1. The base URL where your authentication pages are hosted. You can find your Auth URL under the Backend Integration section for your project at https://app.propelauth.com.
  2. You can manage your api keys under the Backend Integration section for your project.

How it works

The front-end receives an access token. This access token is provided in an Authorization header when an HTTP request is made.

PropelAuth provides you with metadata that you use to validate the access token and figure out who it belongs to. The complexity of fetching the metadata and validating the tokens is hidden in the express library.

Installation

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

$ npm install --save @propelauth/express
$ yarn add @propelauth/express

Initialize

Create a new file with the following code. In the code, initAuth performs a one-time initialization of the library. It will verify your apiKey is correct and fetch the metadata needed to verify access tokens in requireUser, optionalUser, or requireOrgMember.

// propelauth.js
const propelAuth = require("@propelauth/express");
module.exports = propelAuth.initAuth({
    debugMode: true, // (1)
    authUrl: "https://auth.yourdomain.com", // (2)
    apiKey: "YOUR_API_KEY", // (3)
})
  1. 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.
  2. The base URL where your authentication pages are hosted. You can find this under the Backend Integration section for your project at https://app.propelauth.com.
  3. You can manage your api keys under the Backend Integration section for your project.

Protect API routes

requireUser

An Express middleware that will verify the request was made by a valid user. Specifically, it will:

  1. Check that a valid access token was provided. If not, the request is rejected with a 401 status code.
  2. Set user on the Request with the user's information.
app.get("/hello", requireUser, (req, res) => {
    res.text("Hello user with ID " + req.user.userId);
})

The user object looks like:

Property Description
userId The id of the user
orgIdToOrgMemberInfo A dictionary of org ids to metadata about the org. Includes all orgs that the user is in
legacyUserId The original ID of the user, if the user was migrated from an external source

The values of orgIdToOrgMemberInfo are OrgMemberInfo's, with the following fields/functions:

OrgMemberInfo fields/properties Description
orgId The id of the org
orgName The name of the org
urlSafeOrgName A URL-safe version of the name of the org
assignedRole(): string The user's role within the organization. See Roles and Permissions for more details.
permissions(): string[] The user's permissions within the organization. See Roles and Permissions for more details.
isRole(role: string): boolean Returns true if the user's role within the organization matches the role passed in
isAtLeastRole(role: string): boolean Returns true if the user's role within the organization is at least the role passed in. If the hierarchy of roles is Owner => Admin => Member, specifying "Admin" will return True for Admins and Owners, but False for Members.
hasPermission(permission: string): boolean Return true if the user has a specific permission. The users' permissions are derived from their role within this organization.
hasAllPermissions(permissions: string[]): boolean Return true if the user has all the specified permissions. The users' permissions are derived from their role within this organization.

optionalUser

Similar to requireUser, except if an access token is missing or invalid, the request is allowed to continue, but user on the Request will be undefined.

app.get("/hello", optionalUser, (req, res) => {
    if (req.user) {
        res.text("Hello user with ID " + req.user.userId);
    } else {
        res.text("Hello anonymous")
    }
})

requireOrgMember

An Express middleware that will verify the request was made by a valid user that belongs to a specific organization.

// By default, requireOrgMember checks for orgId as a path parameter
app.get("/org/:orgId/hello", 
        requireOrgMember(), 
        (req, res) => {
             res.text("You are in " + req.org.orgName)
        }
)
// Expect users to query with /hello?orgId=...
const orgIdInQueryExtractor = (req) => req.query.orgId;
const requireOrgInQuery = requireOrgMember({
    orgIdExtractor: orgIdInQueryExtractor,
})

app.get("/hello", requireOrgInQuery, (req, res) => {
    res.text("You are in " + req.org.orgName)
})

Specifically, it will:

  1. Check that a valid access token was provided. If not, the request is rejected with a 401 status code.
  2. Set user on the Request with the user's information. See requireUser for what the user object looks like.
  3. Find an id for an organization within the request. By default, it will check Request.params.orgId (a path parameter named orgId).
  4. Check that the user is a member of that organization. If not, the request is rejected with a 403 status code.
  5. Set org on the Request with the organization's information for this user.

Roles and Permissions

A user has a Role within an organization. By default, the available roles are Owner, Admin, or Member, but these can be configured. These roles are also hierarchical, so Owner > Admin > Member.

Roles allow you to control what different users can do within your product. If you want to check a user's role, you can use requireOrgMemberWithExactRole or requireOrgMemberWithMinimumRole.

// Assuming a Role structure of Owner => Admin => Member

app.get("/org/:orgId/admin",
    requireOrgMemberWithExactRole({role: "Admin"}),
    (req, res) => {
        res.text("You are an Admin of " + req.org.orgName)
    }
)

app.get("/org/:orgId/admin_or_owner",
    requireOrgMemberWithMinimumRole({minimumRequiredRole: "Admin"}),
    (req, res) => {
        res.text("You are an Admin of " + req.org.orgName)
    }
)

Permissions are arbitrary strings associated with a role. For example, can_view_billing, ProductA::CanCreate, and ReadOnly are all valid permissions. The PropelAuth dashboard allows you to set up these permissions.

You can use requireOrgMemberWithPermission or requireOrgMemberWithAllPermissions to check for a given permission.

app.get("/org/:orgId/billing",
    requireOrgMemberWithPermission({permission: "can_view_billing"}),
    (req, res) => {
        // TODO: view billing 
    }
)

All of these functions, just like requireOrgMember, can also take in orgIdExtractor, and will set both req.user and req.org on a valid request.

API calls

In addition to protecting API routes, you can make requests to PropelAuth to fetch more information about your users or organizations. You can also create new users, update user metadata, and more.

// Example
const usersResponse = await fetchUsersByQuery({emailOrUsername: "@example.com", orderBy: "LAST_ACTIVE_AT_DESC"})
for (const user of userResponse.users) {
    console.log("Found user " + user)
}

See Express Library Reference for more information on available functionality.

Next Steps

Done with your backend? Next you can deploy to production.