To use request headers in intercepted requests, first declare their types in the HttpSchema. This provides type safety and autocompletion when accessing headers in handler.with(), handler.respond(), and handler.requests.
Request headers are accessed via the .get() method on the headers object of the request.
import { HttpSchema } from '@zimic/http';
type Schema = HttpSchema<{
'/users': {
GET: {
request: {
headers: {
authorization: string;
'accept-language'?: string;
};
};
response: { 200: { body: any[] } };
};
};
}>;
const handler = interceptor
.get('/users')
.with({
headers: {
authorization: 'Bearer my-token',
'accept-language': 'en',
},
})
.respond((request) => {
console.log(request.headers.get('authorization'));
return { status: 200, body: users };
})
.times(1);
// Accessing headers from captured requests
console.log(handler.requests[0].headers.get('authorization'));