Testing and QA · Advanced · 24 min
Verify an API provider against Pact contracts
By Padding · Updated 18 Nov 2026
node:26 (Node.js 26) · Pact JS 17.1.4 · Express 5.3.0
You will make the Express 5 items API prove that it honours the items-web consumer's Pact contract, with state handlers that seed data, a request filter that swaps in a real auth token, a deliberate breaking change that fails verification, and a Pact Broker setup for publishing results and gating deployments.
On this page
A consumer contract test proves that a client sends the requests it says it sends and copes with the responses it expects. That is only half the deal. The other half is provider verification: Pact replays every request in the contract against the real API, and checks that each response matches what the consumer recorded. When both halves pass, the two sides can be released separately without a shared staging environment to catch mismatches.
This tutorial picks up where the consumer tutorial stopped. There, the items-web frontend wrote pacts/items-web-items-api.json, a contract with three interactions against items-api, the items API from the Express 5 REST API tutorial: list the open items with ?done=false, fetch item 999 and get a 404, and add an item. Every request carries a bearer token. You will build a lean version of that API, verify it against the pact, break the contract on purpose, make the same change safely, and then set up the Broker workflow teams use in CI.
If you have not done the consumer tutorial, you can still start here: the pact step includes a copy of the file that tutorial generates.
Verification never tests your API's business rules. It checks only the shapes and statuses the consumer depends on. Keep your own functional tests for the rest.
Step 1 · Set up the provider project
Create a project folder next to the consumer, make it an ES module package, and add two scripts: one to run the API and one to verify it against the pact.
mkdir -p ~/pact-demo/items-api
cd ~/pact-demo/items-api
npm init -y > /dev/null
npm pkg set type=module
npm pkg set scripts.start="node src/server.js"
npm pkg set "scripts.test:pact=node test/verify-pacts.mjs"
npm install --save-exact express@5.3.0
npm install --save-exact --save-dev @pact-foundation/pact@17.1.4Pact JS does its matching in a compiled Rust core, so npm also downloads a native package for your platform (@pact-foundation/pact-core-linux-x64-glibc on most Linux machines, about 18 MB unpacked). On prepaid mobile data, run the install once on Wi-Fi: if you did the consumer tutorial on this machine, npm's cache already holds it and the install needs almost no data.
--save-exact writes 5.3.0 and 17.1.4 into package.json with no ^, so a new release cannot change how verification behaves under you.
Check it worked
npm ls express @pact-foundation/pactThe tree shows express@5.3.0 and @pact-foundation/pact@17.1.4. Pact itself depends on Express 5, so you may see a second, deduped express@5.3.0 line under it.
Step 2 · Build the items API
The routes and status codes follow the REST tutorial: GET /api/items with an optional done filter, GET /api/items/:id with a 404 of {"error":"Item not found"}, and POST /api/items with a 201, a Location header and the new {id, title, done}. Two things are new. The routes need a bearer token, because the consumer sends one. And the code is split into files so verification can reach into it: store.js keeps items in memory and can be reset, which state handlers need; serialise.js turns a stored item into the JSON the API returns, which is the part you will change to break the contract; app.js builds the app from a list of accepted tokens, so tests can pass in their own.
mkdir -p src
cat > src/store.js <<'JS'
const items = new Map()
let nextId = 1
export function reset() {
items.clear()
nextId = 1
}
export function add({ title, done = false }) {
const item = { id: nextId++, title, done }
items.set(item.id, item)
return item
}
export function find(id) {
return items.get(id)
}
export function all() {
return [...items.values()]
}
JS
cat > src/serialise.js <<'JS'
export function toJson(item) {
return {
id: item.id,
title: item.title,
done: item.done,
}
}
JS
cat > src/app.js <<'JS'
import express from 'express'
import * as store from './store.js'
import { toJson } from './serialise.js'
export function createApp({ apiTokens }) {
const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))
// Every /api/items route needs "Authorization: Bearer <token>".
app.use('/api/items', (req, res, next) => {
const header = req.get('Authorization') ?? ''
const token = header.startsWith('Bearer ') ? header.slice(7) : ''
if (!token || !apiTokens.includes(token)) {
return res.status(401).json({ error: 'Missing or invalid token' })
}
next()
})
app.get('/api/items', (req, res) => {
let list = store.all()
if (req.query.done !== undefined) {
if (req.query.done !== 'true' && req.query.done !== 'false') {
return res.status(422).json({ errors: [{ field: 'done', message: 'must be true or false' }] })
}
list = list.filter((item) => item.done === (req.query.done === 'true'))
}
res.json(list.map(toJson))
})
app.get('/api/items/:id', (req, res) => {
const item = store.find(Number(req.params.id))
if (!item) return res.status(404).json({ error: 'Item not found' })
res.json(toJson(item))
})
app.post('/api/items', (req, res) => {
const title = typeof req.body?.title === 'string' ? req.body.title.trim() : ''
if (title.length < 1 || title.length > 100) {
return res.status(422).json({ errors: [{ field: 'title', message: 'must be a string of 1 to 100 characters' }] })
}
const item = store.add({ title })
res.status(201).location(`/api/items/${item.id}`).json(toJson(item))
})
return app
}
JS
cat > src/server.js <<'JS'
import { createApp } from './app.js'
import * as store from './store.js'
const token = process.env.API_TOKEN
if (!token) {
console.error('Set API_TOKEN before starting the server.')
process.exit(1)
}
store.add({ title: 'Learn Express' })
const port = Number(process.env.PORT ?? 8000)
createApp({ apiTokens: [token] }).listen(port, '127.0.0.1', () => {
console.log(`items-api on http://127.0.0.1:${port}`)
})
JSThe server reads its one accepted token from the API_TOKEN environment variable, so no secret is written into the code. Start it in a second terminal. The first line makes a random token for this session:
cd ~/pact-demo/items-api
export API_TOKEN="$(node -e 'console.log(crypto.randomUUID())')"
npm startCheck it worked
Back in your first terminal, list the items without a token, then with one. Copy the token from the second terminal with echo $API_TOKEN there, and set it here:
export API_TOKEN=paste-the-token-herecurl -s -w '\n%{http_code}\n' 'http://127.0.0.1:8000/api/items?done=false'
curl -s -w '\n' -H "Authorization: Bearer $API_TOKEN" 'http://127.0.0.1:8000/api/items?done=false'The first request prints {"error":"Missing or invalid token"} and 401. The second prints [{"id":1,"title":"Learn Express","done":false}].
Stop the server with Ctrl+C in the second terminal. Verification starts its own copy on a free port.
Step 3 · Add the consumer's pact file
In a team the pact arrives from the consumer's CI through a Pact Broker. Here you copy it into a pacts folder. If you did the consumer tutorial, copy the file it generated:
mkdir -p ~/pact-demo/items-api/pacts
cp ~/pact-demo/items-web/pacts/items-web-items-api.json ~/pact-demo/items-api/pacts/Otherwise, write the same file. This is the output of the consumer tutorial's final npx vitest run, unchanged:
mkdir -p pacts
cat > pacts/items-web-items-api.json <<'JSON'
{
"consumer": {
"name": "items-web"
},
"interactions": [
{
"description": "a request for a missing item",
"pending": false,
"providerStates": [
{
"name": "no item has id 999"
}
],
"request": {
"headers": {
"Authorization": [
"Bearer example-token"
]
},
"matchingRules": {
"header": {
"Authorization": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^Bearer .+$"
}
]
}
}
},
"method": "GET",
"path": "/api/items/999"
},
"response": {
"body": {
"content": {
"error": "Item not found"
},
"contentType": "application/json",
"encoded": false
},
"headers": {
"Content-Type": [
"application/json; charset=utf-8"
]
},
"matchingRules": {
"body": {
"$.error": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
}
},
"header": {
"Content-Type": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^application/json(;.*)?$"
}
]
}
}
},
"status": 404
},
"type": "Synchronous/HTTP"
},
{
"description": "a request for open items",
"pending": false,
"providerStates": [
{
"name": "an open item exists",
"params": {
"title": "Buy milk"
}
}
],
"request": {
"headers": {
"Authorization": [
"Bearer example-token"
]
},
"matchingRules": {
"header": {
"Authorization": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^Bearer .+$"
}
]
}
}
},
"method": "GET",
"path": "/api/items",
"query": {
"done": [
"false"
]
}
},
"response": {
"body": {
"content": [
{
"done": false,
"id": 1,
"title": "Buy milk"
}
],
"contentType": "application/json",
"encoded": false
},
"headers": {
"Content-Type": [
"application/json; charset=utf-8"
]
},
"matchingRules": {
"body": {
"$": {
"combine": "AND",
"matchers": [
{
"match": "type",
"min": 1
}
]
},
"$[*].done": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$[*].id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$[*].title": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
}
},
"header": {
"Content-Type": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^application/json(;.*)?$"
}
]
}
}
},
"status": 200
},
"type": "Synchronous/HTTP"
},
{
"description": "a request to add an item",
"pending": false,
"request": {
"body": {
"content": {
"title": "Write a contract"
},
"contentType": "application/json",
"encoded": false
},
"headers": {
"Authorization": [
"Bearer example-token"
],
"Content-Type": [
"application/json"
]
},
"matchingRules": {
"header": {
"Authorization": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^Bearer .+$"
}
]
}
}
},
"method": "POST",
"path": "/api/items"
},
"response": {
"body": {
"content": {
"done": false,
"id": 7,
"title": "Write a contract"
},
"contentType": "application/json",
"encoded": false
},
"headers": {
"Content-Type": [
"application/json; charset=utf-8"
],
"Location": [
"/api/items/7"
]
},
"matchingRules": {
"body": {
"$.done": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
}
},
"header": {
"Content-Type": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^application/json(;.*)?$"
}
]
},
"Location": {
"combine": "AND",
"matchers": [
{
"match": "regex",
"regex": "^/api/items/\\d+$"
}
]
}
}
},
"status": 201
},
"type": "Synchronous/HTTP"
}
],
"metadata": {
"pact-js": {
"version": "17.1.4"
},
"pactRust": {
"ffi": "0.5.8",
"models": "1.3.16"
},
"pactSpecification": {
"version": "4.0"
}
},
"provider": {
"name": "items-api"
}
}
JSONThree things in this file decide how you write the verification:
- Provider states.
a request for open itemsneeds the statean open item exists, with a parametertitle: "Buy milk".a request for a missing itemneedsno item has id 999.a request to add an itemhas no state. Pact asks your provider to set each state up before it replays the request, and you write a handler for each name. - Matching rules. In the list response,
$[*].idmust be an integer and$[*].titleand$[*].donemust have the same type as the example, and$must be an array with at least one element. The values themselves are free. Your API can return any title. It must not drop or rename the field. In the POST response,titlehas no rule, so it must be exactlyWrite a contract, the title the consumer sent. - The Authorization header. The consumer recorded
Bearer example-tokenwith the regex^Bearer .+$, which any bearer token satisfies. Your API rejects that example token, so the verification has to replace it with one the API accepts.
Check it worked
List each interaction with its state, to make sure the JSON parses and you have the names you need for the handlers:
node -e '
const pact = JSON.parse(require("fs").readFileSync("pacts/items-web-items-api.json", "utf8"))
console.log(`${pact.consumer.name} -> ${pact.provider.name}`)
for (const i of pact.interactions) {
const states = (i.providerStates ?? []).map((s) => s.name).join(", ") || "none"
console.log(`${i.description} | ${states}`)
}
'The output is four lines:
items-web -> items-api
a request for a missing item | no item has id 999
a request for open items | an open item exists
a request to add an item | noneStep 4 · Write state handlers and a request filter
Put the state handlers and the request filter in their own module. The verification script imports them, and so can a check that the names match the pact.
mkdir -p test
cat > test/provider-setup.js <<'JS'
import * as store from '../src/store.js'
// One handler per provider state name in the pact. Each starts from an
// empty store so interactions cannot leak data into each other.
export const stateHandlers = {
'an open item exists': async (params) => {
store.reset()
store.add({ title: params.title, done: false })
},
'no item has id 999': async () => {
store.reset()
},
}
// Express middleware on Pact's proxy. Replace the consumer's example token
// with one this API accepts. Requests without the header are left alone.
export function createRequestFilter(token) {
return (req, res, next) => {
if (req.headers.authorization) {
req.headers.authorization = `Bearer ${token}`
}
next()
}
}
JSNow the verification script. It starts the app on a free port, then hands it to Pact's Verifier. Pact runs a small proxy in front of your app. For each interaction it calls the state handler, sends the recorded request through the proxy to your app, and compares the response with the pact.
cat > test/verify-pacts.mjs <<'JS'
import { randomUUID } from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { Verifier } from '@pact-foundation/pact'
import { createApp } from '../src/app.js'
import { stateHandlers, createRequestFilter } from './provider-setup.js'
// A fresh token for this run only. The app accepts it; the filter sends it.
const token = randomUUID()
const server = createApp({ apiTokens: [token] }).listen(0, '127.0.0.1')
await new Promise((resolve) => server.once('listening', resolve))
const { port } = server.address()
const pactFile = fileURLToPath(new URL('../pacts/items-web-items-api.json', import.meta.url))
const verifier = new Verifier({
provider: 'items-api',
providerBaseUrl: `http://127.0.0.1:${port}`,
pactUrls: [pactFile],
stateHandlers,
requestFilter: createRequestFilter(token),
logLevel: 'warn',
})
try {
await verifier.verifyProvider()
console.log('Pact verification passed')
} catch (error) {
console.error('Pact verification failed')
process.exitCode = 1
} finally {
server.close()
}
JSA few choices here are worth copying into your own projects:
- The token is generated per run. The request filter sends it, the app accepts it, and it never appears in the code, the pact or your shell history. If your API checks tokens against an identity provider, issue a short-lived test token in CI and read it from an environment variable instead.
- The filter rewrites only an existing
Authorizationheader. A filter that adds auth to every request would hide a real bug: a consumer that forgets the header on an endpoint that needs it. - Every handler resets the store. Handlers that build on each other's data pass in one order and fail in another.
- The handler uses the state's
titleparameter. The consumer choseBuy milk. If it later asks forPay school feesor a title in Yorùbá, the same handler still works.
The add interaction has no state, so no handler runs before it and the store may still hold an item from the previous interaction. Pact JS logs no state handler found for state: "" for it; that warning is expected. That is fine here: the pact only asks for an integer id, and the Location header only has to match ^/api/items/\d+$.
Check it worked
Compare the handler names with the state names in the pact. Pact JS does not fail on a missing or misspelt handler: it logs no state handler found for state and replays the request anyway. The interaction then fails only if it needed the data, so a state such as no item has id 999, which only needs an empty store, can pass by accident. Check the names directly:
node --input-type=module -e '
import { readFileSync } from "node:fs"
import { stateHandlers } from "./test/provider-setup.js"
const pact = JSON.parse(readFileSync("pacts/items-web-items-api.json", "utf8"))
const needed = new Set(pact.interactions.flatMap((i) => (i.providerStates ?? []).map((s) => s.name)))
for (const name of needed) console.log(`${name in stateHandlers ? "ok " : "MISSING"} ${name}`)
for (const name of Object.keys(stateHandlers)) if (!needed.has(name)) console.log(`unused ${name}`)
'The output is ok no item has id 999 and ok an open item exists, with no MISSING or unused lines. A typo in either file shows up as one of each.
Step 5 · Run the verification
npm run test:pactPact prints a section for the items-web and items-api pair, then one block per interaction. Each block names the description and the state, then lists checks, something like returns a response which has status code 200 (OK) and has a matching body (OK). The run ends with Pact verification passed, and the command exits with status 0.
Check it worked
Confirm the exit status the way CI will:
npm run test:pact > pact-pass.log 2>&1 && echo "verification exit code: 0"The output is verification exit code: 0. Open pact-pass.log and find a request to add an item: its checks are all OK, which means the request filter worked. Without it, every interaction gets a 401 where the pact expects 200, 404 or 201.
Step 6 · Break the contract on purpose
Suppose a developer on the API team decides that title should be called name, and changes only the serialiser. The API's own tests may well pass, because they were updated in the same commit. But listOpenItems in the consumer reads item.title, so the frontend would show blank rows. Write the renamed version:
cat > src/serialise.js <<'JS'
export function toJson(item) {
return {
id: item.id,
name: item.title,
done: item.done,
}
}
JSRun the verification again:
npm run test:pactCheck it worked
The run ends with Pact verification failed, and echo $? straight after it prints 1. Two interactions fail at has a matching body: a request for open items and a request to add an item. Under Failures:, the list mismatch reads $[0] -> Actual map is missing the following keys: title, the add mismatch says the same about $, and the summary line is There were 2 pact failures. a request for a missing item still passes, because its body never had a title. This is the failure a CI pipeline would show before the rename reached the consumer.
Step 7 · Make the change without breaking the consumer
Pact ignores fields the consumer did not ask for, so adding a field is always safe. That gives you a way to rename without a breaking release: send both names, let the consumer move to the new one and publish a new pact, then remove the old name once no deployed consumer version needs it.
cat > src/serialise.js <<'JS'
export function toJson(item) {
return {
id: item.id,
// Kept until every deployed consumer has moved to name.
title: item.title,
name: item.title,
done: item.done,
}
}
JS
npm run test:pactThe question "does any deployed consumer still need title?" is exactly what can-i-deploy answers in the next step. Without a Broker, you would be asking people in a chat channel.
Check it worked
The run ends with Pact verification passed again. To see both fields by hand, start the server in the second terminal with the same commands as before, including the export API_TOKEN=... line, because the server exits without it:
cd ~/pact-demo/items-api
export API_TOKEN="$(node -e 'console.log(crypto.randomUUID())')"
npm startThen, in the first terminal, set API_TOKEN to the new token and fetch item 1:
curl -s -w '\n' -H "Authorization: Bearer $API_TOKEN" http://127.0.0.1:8000/api/items/1The JSON is {"id":1,"title":"Learn Express","name":"Learn Express","done":false}. Stop the server with Ctrl+C when you are done.
Step 8 · Publish results and gate deployments with a Pact Broker
So far the pact is a local file and the result stays on your machine. In a team, both go through a Pact Broker: the open-source Pact Broker you host yourself, or PactFlow, the hosted version. The consumer's CI publishes its pact there, the provider's CI fetches the pacts it must satisfy and publishes its verification result, and each side asks the Broker whether a version is safe to deploy. This step needs a Broker, so treat it as the configuration to add to your CI.
Keep the Broker address and token in CI secrets, exposed as environment variables, never in the code. Change the Verifier options so they fetch pacts from the Broker instead of pactUrls:
const verifier = new Verifier({
provider: 'items-api',
providerBaseUrl: `http://127.0.0.1:${port}`,
pactBrokerUrl: process.env.PACT_BROKER_BASE_URL,
pactBrokerToken: process.env.PACT_BROKER_TOKEN,
// Which consumer pacts to verify: the latest from each consumer's main
// branch, and every version that is deployed or released somewhere.
consumerVersionSelectors: [{ mainBranch: true }, { deployedOrReleased: true }],
// A new pact that this provider has never passed does not fail the build.
enablePending: true,
// Also verify feature-branch pacts created since this date, as pending.
includeWipPactsSince: '2026-11-01',
// Publish only from CI, tied to the commit and branch being built.
publishVerificationResult: process.env.CI === 'true',
providerVersion: process.env.GIT_COMMIT,
providerVersionBranch: process.env.GIT_BRANCH,
stateHandlers,
requestFilter: createRequestFilter(token),
})stateHandlers and createRequestFilter come from test/provider-setup.js, as before. The other options change what a failure means:
- Consumer version selectors decide which pacts you check.
mainBranchcatches what consumers are about to release, anddeployedOrReleasedmakes sure you still support what is live. - Pending pacts stop a consumer's brand-new expectation from turning your build red before you have had a chance to implement it. The result is still published, so the consumer can see it is not yet supported.
- WIP pacts let you verify a consumer's feature branch early, also without failing your build.
- Publishing from CI only keeps a developer's local half-finished run from telling the Broker that a version works.
Before each deployment, ask the Broker whether this provider version is compatible with everything already in the target environment, then record the deployment once it succeeds. Both commands come from the pact-broker executable in the Pact CLI package. The package has several executables, so -p names the package and the word after it names the one to run:
npx --yes -p @pact-foundation/pact-cli@19.0.0 pact-broker can-i-deploy \
--pacticipant items-api --version "$GIT_COMMIT" --to-environment production
npx --yes -p @pact-foundation/pact-cli@19.0.0 pact-broker record-deployment \
--pacticipant items-api --version "$GIT_COMMIT" --environment productionThe CLI reads the Broker address and token from PACT_BROKER_BASE_URL and PACT_BROKER_TOKEN. Environments such as production are created in the Broker first. Run can-i-deploy as a required step of the deploy job, not as a pull request check, because it depends on what is deployed at that moment.
Check it worked
In the Broker's web interface, the items-web and items-api pair shows your provider version with a verification result next to the consumer version it checked. can-i-deploy prints a table of the versions it compared and ends with Computer says yes \o/ and exit code 0 when the deployment is safe, or Computer says no and a non-zero exit code when a deployed consumer still needs something your version no longer provides. Try it by publishing the name-only serialiser from a branch: can-i-deploy to production says no while a consumer version that reads title is deployed.
Step 9 · Clean up
Remove the provider project. Keep ~/pact-demo/items-web if you want to carry on with the consumer side; otherwise remove the whole ~/pact-demo folder. Node.js and npm's cache stay as they were. If you created a Broker account or environment only for this tutorial, delete them in the Broker as well.
cd ~
rm -rf ~/pact-demo/items-apiCheck it worked
ls ~/pact-demo/items-api reports that there is no such file or directory.
Next steps
- Change the consumer side and watch the contract move: write consumer contract tests with Pact.
- Grow the provider back into the full items API with validation and error handling: build a REST API with Express 5.
- Run
npm run test:pacton every pull request alongside your other checks: build a CI quality gate for pull requests.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials