Skip to content

Node Backend Integration

PropelAuth's Node library provides all the building blocks you need to add authentication to any Node backend. For some Node frameworks, like Express, we have built out libraries specifically for them (Express).

For the full Node Library Reference, click here.

Quick example

The following example validates an Authorization HTTP header was sent from a logged-in user.

const propelAuth = require("@propelauth/node");
const {validateAccessTokenAndGetUser} = propelAuth.initBaseAuth({
    authUrl: "YOUR_AUTH_URL", //(1)
    apiKey: "YOUR_API_KEY", //(2)
})

const authorizationHeader = // Get the Authorization header from an HTTP request
validateAccessTokenAndGetUser(authorizationHeader)
    .then(user => {
        console.log(`Got request from user ${user.userId}`);
    }, err => {
        // You can return a 401, or continue the request knowing it wasn't sent from a logged-in user
        console.log(`Unauthorized request ${err}`);
    });
  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 Node library.

Installation

In your Node app, install the @propelauth/node library.

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

Initialize

Create a new file with the following code. In the code, initBaseAuth 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 validateAccessTokenAndGetUser and validateAccessTokenAndGetUserWithOrgInfo.

// propelauth.js
const propelAuth = require("@propelauth/node");
module.exports = propelAuth.initBaseAuth({
    authUrl: "https://auth.yourdomain.com", // (1)
    apiKey: "YOUR_API_KEY", // (2)
})
  1. 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.
  2. You can manage your api keys under the Backend Integration section for your project.

Protect API routes

validateAccessTokenAndGetUser

This function takes in the Authorization HTTP header and verifies the request was made by a valid user. It expects the header to be in the format Bearer ACCESS_TOKEN. If the Authorization HTTP header is malformed or doesn't contain a valid access token, an UnauthorizedException is thrown.

const authorizationHeader = // Get the Authorization header from an HTTP request
try {
    const user = await validateAccessTokenAndGetUser(authorizationHeader)
    console.log(`Got request from user ${user.userId}`);
} catch (err) {
    // You can return a 401, or continue the request knowing it wasn't sent from a logged-in user
    console.log(`Unauthorized request ${err}`);
}

The user object looks like:

{
  // the id of the user whose token was provided
  userId: "2667a646-cdef-49da-8580-47e0d73cffa7",
  // For each organization the user is a member of, this is a dict of the organization's id
  //   to some information about the organization.
  orgIdToOrgMemberInfo: {
    "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4": {
      "orgId": "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4",
      "orgName": "ExampleOrganization",
      // This is the role of the user within that organization. See UserRole for more information
      "userRole": UserRole.Owner,
    }
  }
}

validateAccessTokenAndGetUserWithOrgInfo

This function will verify that a request was made by a valid user AND that user is in an organization. It can optionally also check the user's role within that organization.

Argument Description
Authorization HTTP Header It expects the header to be in the format Bearer ACCESS_TOKEN. If the Authorization HTTP header is malformed or doesn't contain a valid access token, an UnauthorizedException is thrown.
Required Org Info An object with optional fields orgId and orgName. This function will make sure the user who made the request is a member of an organization with the specified orgId and orgName. If the user is NOT a member of the specified organization, a ForbiddenException is thrown.
Minimum Required Role (Optional) Make sure the user has at least this role within the org specified by Required Org Info. If not, a ForbiddenException is thrown.

It returns an object with two fields:

{
    user: //...
    orgMemberInfo: //...
}

The user object has the same structure as the return value of validateAccessTokenAndGetUser.

The orgMemberInfo object looks like:

{
  "orgId": "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4",
  "orgName": "ExampleOrganization",
  "userRole": UserRole.Owner, // (1)
}
  1. This is the role of the user within that organization. See UserRole for more information

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 Node Library Reference for more information on available functionality.

Next Steps

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