Skip to main content

Express.js

This guide shows how to add Zero Ad Network to an existing Express application. If you haven't installed the package yet, start with the Node.js setup guide.

Add the middleware

Register the middleware globally so every route automatically receives the partner header and a populated tokenContext:

src/middleware/zeroad.js
import { Site, FEATURE } from "@zeroad.network/token"

const site = Site({
clientId: "YOUR_CLIENT_ID", // from zeroad.network/publisher/sites
features: [FEATURE.CLEAN_WEB], // or FEATURE.ONE_PASS, or both
})

export function zeroad(req, res, next) {
res.setHeader(site.SERVER_HEADER_NAME, site.SERVER_HEADER_VALUE)
req.tokenContext = site.parseClientToken(req.headers[site.CLIENT_HEADER_NAME])
next()
}
src/app.js
import express from "express"
import { zeroad } from "./middleware/zeroad.js"

const app = express()
app.use(zeroad)

Use the feature flags

req.tokenContext is available in every route handler. Use the flags to tailor the response - non-subscribers get false for all flags and see the site as normal.

app.get("/article/:slug", (req, res) => {
const article = db.getArticle(req.params.slug)
const { DISABLE_CONTENT_PAYWALL, HIDE_ADVERTISEMENTS } = req.tokenContext

res.render("article", {
content: DISABLE_CONTENT_PAYWALL ? article.fullContent : article.excerpt,
showPaywall: !DISABLE_CONTENT_PAYWALL,
showAds: !HIDE_ADVERTISEMENTS,
})
})
// API endpoint
app.get("/api/article/:slug", (req, res) => {
const article = db.getArticle(req.params.slug)
const { DISABLE_CONTENT_PAYWALL } = req.tokenContext

res.json({
title: article.title,
content: DISABLE_CONTENT_PAYWALL ? article.fullContent : article.excerpt,
isPaywalled: !DISABLE_CONTENT_PAYWALL,
})
})

Full working example

A minimal Express app with the integration wired up end-to-end:

src/app.js
import express from "express"
import { Site, FEATURE } from "@zeroad.network/token"

const site = Site({
clientId: "YOUR_CLIENT_ID",
features: [FEATURE.CLEAN_WEB, FEATURE.ONE_PASS],
})

const app = express()

app.use((req, res, next) => {
res.setHeader(site.SERVER_HEADER_NAME, site.SERVER_HEADER_VALUE)
req.tokenContext = site.parseClientToken(req.headers[site.CLIENT_HEADER_NAME])
next()
})

app.get("/", (req, res) => {
const { HIDE_ADVERTISEMENTS, DISABLE_CONTENT_PAYWALL } = req.tokenContext
res.json({ HIDE_ADVERTISEMENTS, DISABLE_CONTENT_PAYWALL })
})

app.listen(3000)

Full runnable examples for Express and other frameworks are in the GitHub examples directory.

What the flags mean

See the tokenContext reference for the full flag list and when each one is true.