Connecting to API Backend

Configuring your SPA to work with a backend API

When building a single page app (SPA) with a backend API, there are a few important considerations. In an application with this architecture, there is typically a JavaScript frontend that uses an API to manage application data and functionality.

Passage Configuration

An "application" in Passage does not specify how that app is implemented. For a SPA and API implementation, you should configure your Passage app as follows:

  • Set the auth origin to the domain of your frontend application

  • Set the redirect URL to the correct path for your app (e.g. "/" or "/dashboard")

  • Generate an API Key on the settings page for use in the backend API code

App Setup

For the frontend app, the key difference is in how the auth tokens get sent to the API. Since the frontend and backend are on different hosts, the cookies set by Passage (psg_auth_token) will not automatically get sent. There are two options:

Manually set the cookie in the axios configuration for authenticated requests to the API.

const authToken = localStorage.getItem("psg_auth_token");
axios
.get(`${API_URL}/${PATH}`, {
  headers: {
    Cookie: `psg_auth_token=${authToken}`,
  },
  withCredentials: true,
})

To use this option, you will need to set the withCredentials CORs option on the backend API server as well.

const express = require("express");
const Passage = require("@passageidentity/passage-node");
const cors = require("cors");

const app = express();
app.use(express.json());
// cors setup for express API
app.use(
  cors({
    origin: CLIENT_URL,
    credentials: true,
  })
);

// use default auth strategy for passage
const passage = new Passage({
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
});

Header Auth

The most common options for SPAs with backend APIs is to send auth tokens in the "Authorization" request header. This can be done from JavaScript as shown below. Note that the the default CORS settings will work just fine for this authentication type.

const authToken = localStorage.getItem("psg_auth_token");
axios
.get(`${API_URL}/${PATH}`, {
  headers: {
    Authorization: `Bearer ${authToken}`,
  },
})

No additional server configurations are required, but make sure to set the auth strategy on the Passage class.

const passage = new Passage({
  appID: process.env.PASSAGE_APP_ID,
  apiKey: process.env.PASSAGE_API_KEY,
  authStrategy: Passage.HEADER_AUTH, // default is Passage.COOKIE_AUTH
});

Examples

React + NodeJS

Last updated