How do you handle dynamic authentication tokens and dynamic headers in Pact contract tests without leaking secrets?
Asked by The SDET Playbook
Asked Sep 28, 2026Viewed 0 times
How do you handle dynamic authentication tokens and dynamic headers in Pact contract tests without leaking secrets?
Asked by The SDET Playbook
Sign in to answer and to vote.
Keep real tokens out of the pact file entirely. On the consumer side, describe the header's format with a matcher and a harmless example value:
const { MatchersV3 } = require('@pact-foundation/pact');
provider
.uponReceiving('a request for user 42')
.withRequest({
method: 'GET',
path: '/users/42',
headers: { Authorization: MatchersV3.regex('^Bearer .+$', 'Bearer example-token') },
});
On the provider side, replace the example token with a valid one just before each request reaches the provider, using the verifier's requestFilter, which works like Express middleware:
new Verifier({
provider: 'UserService',
providerBaseUrl: 'http://localhost:3000',
requestFilter: (req, res, next) => {
if (req.headers.authorization) {
req.headers.authorization = `Bearer ${getTestToken()}`;
}
next();
},
});
getTestToken() issues a short-lived token for a test user in the provider's test environment. That keeps credentials out of the contract, out of the Broker and out of the repository. Contract tests check that the consumer sends a correctly shaped header, not that authentication works; test authentication and authorization separately in the provider's own tests.
Sources: Pact JS matching, Pact JS provider