Skip to main content

Integrate authentication into Node.js / Express.js

This guide shows how to create a simple Express.js application and secure it with authentication powered by Ory. The guide provides the setup for using Ory Network, but the code can be used with both Ory Network and self-hosted Ory software.

This guide is perfect for you if:

  1. You have Express.js installed.
  2. You want to build an app using Express.js.
  3. You want to give access to your application to signed-in users only.

Before you start, watch this video to see the user flow you're going to implement:

info

You can find the code of the sample application here.

Create Express.js app

Create a new Express.js project:

mkdir your-project
cd your-project

npm init -y

npm install express
npm install -D nodemon

Create a new Ory project

  1. Create an Ory account at https://console.ory.sh
  2. Create a new project at https://console.ory.sh/projects/create
  3. Go to your project settings
https://console.ory.sh/projects/<id>/settings

Project settings tab

  1. Note down your project credentials (ID, slug, endpoint)
https://console.ory.sh/projects/<id>/settings

Project credentials

Install Ory SDK and CLI

To interact with Ory's APIs, install the Ory SDK and CLI:

npm i --save @ory/client-fetch @ory/cli

Why do I need the Ory CLI

The Ory security model uses HTTP cookies to manage sessions, tokens, and cookies. Because of browser security measures like CORS, Ory APIs must be exposed on the same domain as your application.

In the case of this example the application runs on your local machine. The cookie domain is localhost.

info

When developing locally, use either localhost or 127.0.0.1, but not both. Although technically these mean the same thing, they're different cookie domains.

Using both interchangeably in your code causes problems, as Ory APIs will not receive the cookies when they are set on a different domain.

Ory CLI provides a convenient way to configure and manage projects. Additionally, the CLI provides Ory Proxy - a reverse proxy that rewrites cookies to match the domain your application is currently on.

To make Ory APIs and your application available on the same domain, Ory Proxy mirrors Ory endpoints and rewrites cookies to match the domain correct domain.

As a result, the domain of the cookies is set correctly to the domain you run the app on instead of <your-project-slug>.projects.oryapis.com.

By using the Proxy, you can easily connect the application you're developing locally to Ory Network and consume the APIs without additional configuration or the self-hosting any Ory services.

tip

To learn more about the Ory Proxy, read the dedicated section of the Ory CLI documentation.

Update the npm scripts

Now that the Ory CLI is installed, create a new npm script to run the proxy server:

package.json
{
"name": "protect-page-login",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "nodemon index.js",
"proxy": "ory proxy --project $ORY_PROJECT_ID --port 4000 http://localhost:3000/"
},
"dependencies": {

This requires the express app (npm run start) to run on port 3000. However, the app has to be accessed through the port 4000 (http://localhost:4000).

Require login to access the home page

Next we add a session check to the default home page of the example application. The highlighted code is what we added to check whether the user is signed in, and redirect them to the login page if not:

index.js
const app = require("express")()
const sdk = require("@ory/client-fetch")

const ory = new sdk.FrontendApi(
new sdk.Configuration({
basePath: process.env.ORY_SDK_URL || "http://localhost:4000/.ory",
}),
)

const requireAuth = async (req, res, next) => {
try {
const session = await ory.toSession({ cookie: req.header("cookie") })
req.session = session
next()
} catch (error) {
res.redirect("/.ory/ui/login")
}
}

app.get("/", requireAuth, (req, res) => {
res.json(req.session)
})

const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Server is running on port ${port}`))

Run your Express.js app

Great, that's it. Let's run your application. Start the Express.js server

npm run dev

Next open a new terminal window and start the Ory Proxy. Upon first start, the Ory Proxy will ask you to log into your Ory Console account.

ORY_PROJECT_ID=<YOUR_PROJECT_ID> npm run proxy

Replace <YOUR_PROJECT_ID> with your actual Ory Project ID from the Ory Console.

To access the Express.js app through the ORY proxy open http://localhost:4000 in your browser. You are presented with Ory's Sign In page. Let's click on sign up and create your first user.

Go to production

You can use many different approaches to go to production with your application. You can deploy it on Kubernetes, AWS, a VM, a RaspberryPi - the choice is yours! To connect the application to your Ory project, the app and Ory APIs must be available under the same common domain, for example https://ory.example.com and https://www.example.com.

You can easily connect Ory to your subdomain. To do that, add a Custom Domain to your Ory Network project.

With the custom domain set up, you don't need to use Ory Proxy or Ory Tunnel to interact with Ory APIs. Instead, use the configured custom domain in your SDK calls:

var sdk = require("@ory/client")

var ory = new sdk.FrontendApi(
new sdk.Configuration({
basePath: "https://ory.example.org",
baseOptions: {
// Ensures that cookies are included in CORS requests:
withCredentials: true,
},
}),
)