@imgix/js-core
is a JavaScript library for generating image URLs with imgix that can be used in browser or server-side settings.
Ixlib
Param on Every Request?@imgix/js-core can be installed via npm:
npm install @imgix/js-core
Depending on your module system, using @imgix/js-core is done a few different ways. The most common entry point will be the ImgixClient
class. Whenever you provide data to ImgixClient
, make sure it is not already URL-encoded, as the library handles proper encoding internally.
const ImgixClient = require('@imgix/js-core');
const client = new ImgixClient({
domain: 'testing.imgix.net',
secureURLToken: '<SECURE TOKEN>',
});
const url = client.buildURL('/path/to/image.png', {
w: 400,
h: 300,
});
console.log(url); // => "https://testing.imgix.net/users/1.png?w=400&h=300&s=…"
import ImgixClient from '@imgix/js-core';
const client = new ImgixClient({
domain: 'testing.imgix.net',
secureURLToken: '<SECURE TOKEN>',
});
const url = client.buildURL('/path/to/image.png', { w: 400, h: 300 });
console.log(url); // => 'https://testing.imgix.net/users/1.png?w=400&h=300&s=…'
var client = new ImgixClient({
domain: 'testing.imgix.net',
// Do not use signed URLs with `secureURLToken` on the client side,
// as this would leak your token to the world. Signed URLs should
// be generated on the server.
});
var url = client.buildURL('/path/to/image.png', { w: 400, h: 300 });
console.log(url); // => "https://testing.imgix.net/users/1.png?w=400&h=300"
The following options can be used when creating an instance of ImgixClient
:
domain
: String, required. The imgix domain that will be used when constructing URLs. Defaults to null
.useHTTPS
: Boolean. Specifies whether constructed URLs should use the HTTPS protocol. Defaults to true
.includeLibraryParam
: Boolean. Specifies whether the constructed URLs will include an ixlib
parameter. Defaults to true
.secureURLToken
: String. When specified, this token will be used to sign images. Read more about securing images on the imgix Docs site. Defaults to null
.
secureURLToken
option should only be used in server-side applications to prevent exposing your secure token. :warning:ImgixClient.buildURL(path, params, options)
path
: String, required. A full, unencoded path to the image. This includes any additional directory information required to locate the image within a source.params
: Object. Any number of imgix rendering API parameters.options
: Object. Any number of modifiers, described below:
disablePathEncoding
: Boolean. Disables encoding logic applied to the image path.encoder
: Function. Applies custom logic to encode the image path and query parameters.Construct a single image URL by passing in the image path
and any rendering API parameters.
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const url = client.buildURL('folder/image.jpg', {
w: 1000,
});
Returns: an image URL as a string.
https://testing.imgix.net/folder/image.jpg?w=1000&ixlib=js-...
ImgixClient.buildSrcSet(path, params, options)
path
: String, required. A full, unencoded path to the image. This includes any additional directory information required to locate the image within a source.params
: Object. Any number of imgix rendering API parameters.options
: Object. Any number of srcset modifiers, described below:
The @imgix/js-core module allows for generation of custom srcset
attributes, which can be invoked through buildSrcSet()
. By default, the srcset
generated will allow for responsive size switching by building a list of image-width mappings.
const client = new ImgixClient({
domain: 'testing.imgix.net',
secureURLToken: 'my-token',
});
const srcset = client.buildSrcSet('image.jpg');
console.log(srcset);
Returns: A srcset
attribute value as a string.
https://testing.imgix.net/image.jpg?w=100&s=e2e581a39c917bdee50b2f8689c30893 100w,
https://testing.imgix.net/image.jpg?w=116&s=836e0bc15da2ad74af8130d93a0ebda6 116w,
https://testing.imgix.net/image.jpg?w=134&s=688416d933381acda1f57068709aab79 134w,
...
https://testing.imgix.net/image.jpg?w=7400&s=91779d82a0e1ac16db04c522fa4017e5 7400w,
https://testing.imgix.net/image.jpg?w=8192&s=59eb881b618fed314fe30cf9e3ec7b00 8192w
Specifying either a w
or a h
parameter to buildSrcSet()
will create a DPR-based srcset. This DPR-based srcset allows for the fixed-sized image to be served at different resolutions (i.e. at different pixel densities).
const client = new ImgixClient({
domain: 'testing.imgix.net',
secureURLToken: 'my-token',
});
const srcset = client.buildSrcSet('image.jpg', {
h: 800,
ar: '3:2',
fit: 'crop',
});
console.log(srcset);
Will produce the following attribute value:
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=1&s=3d754a157458402fd3e26977107ade74 1x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=2&s=a984ad1a81d24d9dd7d18195d5262c82 2x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=3&s=8b93ab83d3f1ede4887e6826112d60d1 3x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=4&s=df7b67aa0439588edbfc1c249b3965d6 4x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=5&s=7c4b8adb733db37d00240da4ca65d410 5x
By default, this library generates a srcset
with pixel density values of 1
through 5
.
These target ratios can be controlled by using the devicePixelRatios
parameters.
const client = new ImgixClient({
domain: 'testing.imgix.net',
secureURLToken: 'my-token',
});
const srcset = client.buildSrcSet(
'image.jpg',
{
h: 800,
ar: '3:2',
fit: 'crop',
},
{
devicePixelRatios: [1, 2],
},
);
console.log(srcset);
Will result in a smaller srcset.
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=1&s=3d754a157458402fd3e26977107ade74
1x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=2&s=a984ad1a81d24d9dd7d18195d5262c82
2x
For more information to better understand srcset
, we highly recommend Eric Portis' "Srcset and sizes" article which goes into depth about the subject.
In situations where specific widths are desired when generating srcset
pairs, a user can specify them by passing an array of positive integers as widths
to the third options object:
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const srcset = client.buildSrcSet(
'image.jpg',
{},
{ widths: [100, 500, 1000, 1800] },
);
console.log(srcset);
Will generate the following srcset
of width pairs:
https://testing.imgix.net/image.jpg?w=100 100w,
https://testing.imgix.net/image.jpg?w=500 500w,
https://testing.imgix.net/image.jpg?w=1000 1000w,
https://testing.imgix.net/image.jpg?w=1800 1800w
Note: that in situations where a srcset
is being rendered as a fixed image, any custom widths
passed in will be ignored. Additionally, if both widths
and a widthTolerance
are passed to the buildSrcSet
method, the custom widths list will take precedence.
The srcset
width tolerance dictates the maximum tolerated size difference between an image's downloaded size and its rendered size. For example: setting this value to 0.1 means that an image will not render more than 10% larger or smaller than its native size. In practice, the image URLs generated for a width-based srcset attribute will grow by twice this rate. A lower tolerance means images will render closer to their native size (thereby increasing perceived image quality), but a large srcset list will be generated and consequently users may experience lower rates of cache-hit for pre-rendered images on your site.
By default this rate is set to 8 percent, which we consider to be the ideal rate for maximizing cache hits without sacrificing visual quality. Users can specify their own width tolerance by providing a positive scalar value as widthTolerance
to the third options object:
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const srcset = client.buildSrcSet('image.jpg', {}, { widthTolerance: 0.2 });
console.log(srcset);
In this case, the width_tolerance
is set to 20 percent, which will be reflected in the difference between subsequent widths in a srcset pair:
https://testing.imgix.net/image.jpg?w=100 100w,
https://testing.imgix.net/image.jpg?w=140 140w,
https://testing.imgix.net/image.jpg?w=196 196w,
...
https://testing.imgix.net/image.jpg?w=8192 8192w
In certain circumstances, you may want to limit the minimum or maximum value of the non-fixed srcset
generated by the buildSrcSet()
method. To do this, you can pass in an options object as a third argument, providing positive integers as minWidth
and/or maxWidth
attributes:
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const srcset = client.buildSrcSet(
'image.jpg',
{},
{ minWidth: 500, maxWidth: 2000 },
);
console.log(srcset);
Will result in a smaller, more tailored srcset.
https://testing.imgix.net/image.jpg?w=500 500w,
https://testing.imgix.net/image.jpg?w=580 580w,
https://testing.imgix.net/image.jpg?w=672 672w,
https://testing.imgix.net/image.jpg?w=780 780w,
https://testing.imgix.net/image.jpg?w=906 906w,
https://testing.imgix.net/image.jpg?w=1050 1050w,
https://testing.imgix.net/image.jpg?w=1218 1218w,
https://testing.imgix.net/image.jpg?w=1414 1414w,
https://testing.imgix.net/image.jpg?w=1640 1640w,
https://testing.imgix.net/image.jpg?w=1902 1902w,
https://testing.imgix.net/image.jpg?w=2000 2000w
Remember that browsers will apply a device pixel ratio as a multiplier when selecting which image to download from a srcset
. For example, even if you know your image will render no larger than 1000px, specifying options: { max_srcset: 1000 }
will give your users with DPR higher than 1 no choice but to download and render a low-resolution version of the image. Therefore, it is vital to factor in any potential differences when choosing a minimum or maximum range.
Note: that according to the imgix API, the maximum renderable image width is 8192 pixels.
This library will automatically append a variable q
parameter mapped to each dpr
parameter when generating a fixed-image srcset. This technique is commonly used to compensate for the increased filesize of high-DPR images. Since high-DPR images are displayed at a higher pixel density on devices, image quality can be lowered to reduce overall filesize without sacrificing perceived visual quality. For more information and examples of this technique in action, see this blog post.
This behavior will respect any overriding q
value passed in as a parameter. Additionally, it can be disabled altogether by passing { disableVariableQuality: true }
to the third argument of buildSrcSet()
.
This behavior specifically occurs when a fixed-size image is rendered, for example:
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const srcset = client.buildSrcSet('image.jpg', { w: 100 });
console.log(srcset);
Will generate a srcset with the following q
to dpr
mapping:
https://testing.imgix.net/image.jpg?w=100&dpr=1&q=75 1x,
https://testing.imgix.net/image.jpg?w=100&dpr=2&q=50 2x,
https://testing.imgix.net/image.jpg?w=100&dpr=3&q=35 3x,
https://testing.imgix.net/image.jpg?w=100&dpr=4&q=23 4x,
https://testing.imgix.net/image.jpg?w=100&dpr=5&q=20 5x
Quality parameters is overridable for each dpr
by passing variableQualities
parameters.
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const srcset = client.buildSrcSet(
'image.jpg',
{ w: 100 },
{ variableQualities: { 1: 45, 2: 30, 3: 20, 4: 15, 5: 10 } },
);
console.log(srcset);
Will generate the following custom q
to dpr
mapping:
https://testing.imgix.net/image.jpg?w=100&dpr=1&q=45 1x,
https://testing.imgix.net/image.jpg?w=100&dpr=2&q=30 2x,
https://testing.imgix.net/image.jpg?w=100&dpr=3&q=20 3x,
https://testing.imgix.net/image.jpg?w=100&dpr=4&q=15 4x,
https://testing.imgix.net/image.jpg?w=100&dpr=5&q=10 5x
This library will encode by default all paths passed to both buildURL
and buildSrcSet
methods. To disable path encoding, pass { disablePathEncoding: true }
to the third argument options
of buildURL()
or buildSrcSet()
.
const client = new ImgixClient({
domain: 'testing.imgix.net',
});
const src = client.buildURL(
'file+with%20some+crazy?things.jpg',
{},
{ disablePathEncoding: true },
);
console.log(src);
const srcset = client.buildSrcSet(
'file+with%20some+crazy?things.jpg',
{},
{ disablePathEncoding: true },
);
console.log(srcset);
Normally this would output a src of https://testing.imgix.net/file%2Bwith%2520some%2Bcrazy%3Fthings.jpg
, but since path encoding is disabled, it will output a src of https://testing.imgix.net/file+with%20some+crazy?things.jpg
.
This library will encode by default using encodeURI()
, encodeURIComponent()
, or a combination of the two depending on the image path and parameters.
You can define a custom encoding function in buildURL's
options` object if you wish to override this behavior. Note that encoding your own URL can result in a URL that is not recognized by the imgix rendering API.
const ImgixClient = require("@imgix/js-core");
const client = new ImgixClient({
domain: 'test.imgix.com',
secureURLToken: 'xxxxxxxx',
});
client.buildURL(
"https://proxy.imgix.net/image.jpg",
{
"txt": "test!(')*"
},
{
encoder: (path) => encodeURI(path).replace("'", "%27")
}
)
/*
output:
https://proxy.imgix.net/image.jpg?txt=test!(%27)
*/
The custom encoder also accepts a second optional parameter key
which allows users to modify how query parameters are encoded. This parameter does not affect the custom encoding logic of the image path.
const ImgixClient = require("@imgix/js-core");
const client = new ImgixClient({
domain: 'test.imgix.com',
secureURLToken: 'xxxxxxxx',
});
client.buildURL(
"https://proxy.imgix.net/image.jpg",
{
"txt": "test!(')*"
},
{
encoder: (value, key) => key?.substr(-2) === '64' ? Base64.encodeURI(value) : value.replace(' ', "+")
}
)
If you are using a Web Proxy Source, all you need to do is pass the full image URL you would like to proxy to @imgix/js-core
as the path, and include a secureURLToken
when creating the client. @imgix/js-core
will then encode this full URL into a format that imgix will understand, thus creating a proxy URL for you.
import ImgixClient from '@imgix/js-core';
const client = new ImgixClient({
domain: 'my-proxy-domain.imgix.net',
secureURLToken: '<token>',
});
client.buildURL('https://example.com/image-to-proxy.jpg', {});
client.buildSrcSet('https://example.com/image-to-proxy.jpg', {});
Ixlib
Param on Every Request?For security and diagnostic purposes, we sign all requests with the language and version of library used to generate the URL.
This can be disabled by passing a falsy value for the includeLibraryParam
option to new ImgixClient
:
new ImgixClient({
domain: 'my-source.imgix.net',
includeLibraryParam: false,
});
Users looking for client library support for the imgix management API should use the imgix-management-js library. These two projects may be merged at a future date.
@imgix/js-core uses mocha for testing. Here’s how to run those tests:
npm test