imgix-url-builder
Version:
JavaScript/TypeScript Imgix URL builders for browsers and Node.js
71 lines (69 loc) • 2.47 kB
text/typescript
import type { BuildWidthSrcSetParams } from "../buildWidthSrcSet";
import { buildSignedURL } from "./buildSignedURL";
/**
* Builds an `<img>` `srcset` attribute value for a given set of widths. It can
* also optinally apply Imgix URL API parameters to the URLs. The URLs are
* signed by appending a signature to their URL parameters. This locks the URLs
* and their parameters to the signature to prevent URL tampering.
*
* The `width` URL parameter will be applied for each `srcset` entry. If a
* `width` or `w` parameter is provided to the `params` parameter, it will be
* ignored.
*
* **Important**: This function should only be used in a trusted environment and
* never in a browser. The `secureURLToken` parameter is a secret and should not
* be exposed to the public.
*
* @example
*
* ```ts
* const srcset = buildSignedWidthSrcSet(
* "https://example.imgix.net/image.png",
* "example-token",
* { widths: [400, 800, 1600] },
* );
* // => https://example.imgix.net/image.png?width=400&s=def3e221c3f4c4debda091b8e49420ea 400w,
* // https://example.imgix.net/image.png?width=800&s=f12c7c39333410c10c2930b57116a943 800w,
* // https://example.imgix.net/image.png?width=1600&s=3a975b5087ab7ad2ab91fe66072fd628 1600w
* ```
*
* @example
*
* ```ts
* const srcset = buildSignedWidthSrcSet(
* "https://example.imgix.net/image.png",
* "example-token",
* {
* widths: [400, 800, 1600],
* sat: -100,
* },
* );
* // => https://example.imgix.net/image.png?width=400&sat=-100&s=def3e221c3f4c4debda091b8e49420ea 400w,
* // https://example.imgix.net/image.png?width=800&sat=-100&s=f12c7c39333410c10c2930b57116a943 800w,
* // https://example.imgix.net/image.png?width=1600&sat=-100&s=3a975b5087ab7ad2ab91fe66072fd628 1600w
* ```
*
* @param url - Full absolute URL to the Imgix image.
* @param secureURLToken - The secret secure URL token for the image's Imgix
* source.
* @param params - An object of Imgix URL API parameters. The `widths` parameter
* defines the resulting `srcset` widths.
*
* @returns A `srcset` attribute value for `url` with the given Imgix URL API
* parameters applied.
*/
export const buildSignedWidthSrcSet = (
url: string,
secureURLToken: string,
{ widths, ...params }: BuildWidthSrcSetParams,
): string => {
return widths
.map((width) => {
return `${buildSignedURL(url, secureURLToken, {
...params,
w: undefined,
width,
})} ${width}w`;
})
.join(", ");
};