Response Headers
Overviewri:link
The Middleware Response Headers extension enables the addition of custom response headers, which can be particularly useful for managing application caching or establishing security rules.
With this extension, you can overwrite or set headers for individual API methods or apply them globally across your application. It can be implemented for any Unified Alokai backend, and third-party tool integration.
How does it work?ri:link
The extension can be used in two ways:
- Locally: to set custom headers for individual API methods
- Globally: to set
Cache-Control
header for all the API methods
Internally, the extension will identify all GET-type methods and add/overwrite the headers to their responses using the afterCall
hook. Read the Middleware Extensions guide to learn more about the internals of an extension.
Installationri:link
To install the extension, run the following command in your apps/storefront-middleware
folder:
yarn add @vsf-enterprise/middleware-headers
Configurationri:link
To configure the extension for a specific integration, add the following code to your middleware.config.js
file:
import headersExtension from '@vsf-enterprise/middleware-headers';
import { extensionConfig } from './extensionConfig';
export default {
integrations: {
// ... other integrations
[integrationName]: {
extensions: (extensions: ApiClientExtension[]) => [
...extensions,
headersExtension({ ...extensionConfig }),
// ... other extensions
]
}
},
};
Usageri:link
Local Usageri:link
Now, in the extensionConfig.ts
file, you can set up your headers for individual API methods.
export const extensionConfig = {
methods: {
[apiMethodName]: {
response: {
headers: {
'Cache-Control': 'your-rules',
// ... other headers
}
}
}
}
};
Here, your IDE will be able to suggest the available API methods and their names. You can also define your custom ones, making sure that the method name matches the one from the API.
To provide proper types inference you can use generic type to define them, like this.
headersExtension<'fooMethod' | 'barMethod'>({ ...config }),
Global Usageri:link
To apply global Cache-Control
rules on every API method, you can set the cacheControl
property in your extension's configuration.
export const extensionConfig = {
cacheControl: 'your-rules',
};
The extension also ships with a predefined cacheControlRules
value. You can opt-in to using this by setting cacheControl
to true.
/* This is just for presentation purposes; the code is part of the package internals. */
const SHORT_TTL = 60 * 5; // One hour
const cacheControlRules = `public, max-age=0, s-maxage=${SHORT_TTL}, must-revalidate`;
export const extensionConfig = {
cacheControl: true,
};
Signatureri:link
function extension<T extends string>(
config?: ExtensionConfig<T>
): ApiClientExtension;