Node.js

Authenticate requests and manage Passage users with Node.js.

Installation

To learn more, see our Github repo with up to date requirements and installation steps.

Requirements: Passage App ID and API Key from Console

npm package: @passageidentity/passage-node

Authenticating Requests

Passage makes it easy to associate an HTTP request with an authenticated user. The following code can be used to validate that a request was made by an authenticated user.

import Passage from "@passageidentity/passage-node";

// Passage requires an App ID and, optionally, an API Key
const passageConfig = {
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
};

// Authentication using Passage class instance
let passage = new Passage(passageConfig);
app.get("/authenticatedRoute", async(req, res) => {
  try {
    // Authenticate request using Passage
    let userID = await passage.authenticateRequest(req);
    if (userID) {
      // User is authenticated
      let userData = await passage.user.get(userID);
      console.log(userData);
    }
  } catch (e) {
    // Authentication failed
    console.log(e);
    res.send("Authentication failed!");
  }
});

By default, Passage looks for the user JWT from a cookie that is set by the Passage Element ( psg_auth_token ). If your application uses Authorization headers instead, you can pass the following option to the Passage Node SDK.

const passageConfig = {
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
  authStrategy: "HEADER",
};
psg = new Passage(passageConfig)

Authenticating a Request With Express.js Middleware

If you use Express.js, Passage provides a middleware that can be used directly. This middleware will authenticate a request and return a 401 Unauthorized if the token is invalid. If it succeeds, the Passage User ID will be available in the response. The following code shows how the Passage middleware can be used in an Express.js application.

import Passage from "@passageidentity/passage-node";

const passageConfig = {
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
};

// example of passage middleware
let passage = new psg(passageConfig);
let passageAuthMiddleware = (() => {
    return async (req, res, next) => {
        try {
            let userID = await passage.authenticateRequest(req);
            if (userID) {
              // user authenticated
              res.userID = userID;  
              next();
            }
        } catch(e) {
            // failed to authenticate
            // we recommend returning a 401 or other "unauthorized" behavior
            console.log(e);
            res.status(401).send('Could not authenticate user!');
        }
    }
})();

app.get("/authenticatedRoute", passageAuthMiddleware, async(req, res) => {
    let userID = res.userID
    // do authenticated things... 
});

If you are not using passage-node in a request context, or your application is passing the JWT in a custom way, you can pass the JWT directly to the validAuthToken method to perform validation.

const userID = await passage.validAuthToken(token);
if (userID) {
  //authenticated
}
// otherwise, unauthorized

App Information

The Passage SDK provides a way to retrieve information about an app.

import Passage from "@passageidentity/passage-node";

let passageConfig = {
  appID: "YOUR_APP_ID"
};
let passage = new Passage(passageConfig);
let passageAppInfo = passage.getApp();

console.log(passageAppInfo);

User Management

In addition to authenticating requests, the Passage Node SDK also provides a way to securely manage your users. These functions require authentication using a Passage API key. API keys can be managed in the Passage Console.

The functionality currently available on a user is:

  • Get a user's information (including any defined user metadata)

  • Activate or deactivate a user (a deactivated user will not be able to log in)

  • Update a user's information (email address or phone number)

  • Delete a user

  • Create a user

Passage API Keys are sensitive! You should store them securely along with your other application secrets.

import Passage from "@passageidentity/passage-node";

const passageConfig = {
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
};

let passage = new Passage(passageConfig);
//
//...middleware here...
//

app.get("/authenticatedRoute", passageAuthMiddleware, async(req, res) => {
  let userID = res.userID;
  let passageUser = await passage.user.get(userID);
  console.log(passageUser.email)
});

Field

Type

id

string

email

string

phone

string

active

boolean

email_verified

boolean

created_at

datetime

last_login_at

datetime

webauthn

boolean

user_metadata

map

webauthn_devices

array of strings (e.g. "Mac OS X")

recent_events

array of PassageEvents

User Device Management

The functionality currently available is:

  • List all devices for a user

  • Revoke a particular device from a user

import Passage from "@passageidentity/passage-node";

const passageConfig = {
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
};

let passage = new Passage(passageConfig);
//
//...middleware here...
//

app.get("/authenticatedRoute", passageAuthMiddleware, async(req, res) => {
  let userID = res.userID;
  let devices = await passage.user.listDevices(userID);
  console.log(devices)
});

The Node.js SDK can be used to generate custom magic links for users, that can be embedded into any content medium. To learn more, see our full guide on Embedded Magic Links.

import Passage from "@passageidentity/passage-node";

let passageConfig = {
  appID: "YOUR_APP_ID",
  apiKey: "YOUR_API_KEY",
};
let passage = new Passage(passageConfig);
let magicLink = passage.createMagicLink({
  email: "[email protected]",
  redirect_url: "/custom-path/1234", 
});

// use magicLink.url
console.log(magicLink.url)

Last updated