Gathering detailed insights and metrics for @imgix/gatsby
Gathering detailed insights and metrics for @imgix/gatsby
Gathering detailed insights and metrics for @imgix/gatsby
Gathering detailed insights and metrics for @imgix/gatsby
npm install @imgix/gatsby
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
30 Stars
916 Commits
6 Forks
10 Watching
13 Branches
11 Contributors
Updated on 06 Mar 2024
TypeScript (89.44%)
CSS (5.72%)
JavaScript (4.84%)
Dockerfile (0.01%)
Cumulative downloads
Total Downloads
Last day
-3.9%
1,253
Compared to previous day
Last week
-8.6%
6,164
Compared to previous week
Last month
9.4%
27,346
Compared to previous month
Last year
-28.4%
282,624
Compared to previous year
12
3
36
@imgix/gatsby
is a multi-faceted plugin to help the developer use imgix with Gatsby.
Before you get started with this library, it's highly recommended that you read Eric Portis' seminal article on srcset
and sizes
. This article explains the history of responsive images in responsive design, why they're necessary, and how all these technologies work together to save bandwidth and provide a better experience for users. The primary goal of this library is to make these tools easier for developers to implement, so having an understanding of how they work will significantly improve your experience with this library.
Below are some other articles that help explain responsive imagery, and how it can work alongside imgix:
Integrating imgix with Gatsby provides a few key advantages over the core image experience in Gatsby:
Firstly, this library requires an imgix account, so please follow this quick start guide if you don't have an account.
Then, install this library with the following commands, depending on your package manager.
npm install @imgix/gatsby
yarn add @imgix/gatsby
Finally, check out the section in the usage guide below that most suits your needs.
To find what part of this usage guide you should read, select the use case below that best matches your use case:
imgixImage
APIThis feature can be best thought of as a replacement for gatsby-image-sharp, for images that are provided by Gatsby Source plugins, such as Contentful or Prismic. These plugins provide data that is accessed with the Gatsby GraphQL API, with images that are stored on the internet. This plugin can transform those images using imgix, and serve them to your customers.
This source must be configured in your gatsby-config
file as follows:
1// Add to start of file 2const { ImgixSourceType } = require('@imgix/gatsby'); 3 4module.exports = { 5 //... 6 plugins: [ 7 // your other plugins here 8 { 9 resolve: `@imgix/gatsby`, 10 options: { 11 // This is the domain of your imgix source, which can be created at 12 // https://dashboard.imgix.com/. 13 // Required for "Web Proxy" imgix sources. 14 domain: 'example.imgix.net', 15 16 // This is the source's secure token. Can be found under the "Security" 17 // heading in your source's configuration page, and revealed by tapping 18 // "Show Token". Required for web-proxy sources. 19 secureURLToken: 'abcABC123', 20 21 // This configures the plugin to work in proxy mode. 22 // Can be AmazonS3, GoogleCloudStorage, MicrosoftAzure, or WebFolder. 23 sourceType: ImgixSourceType.WebProxy, 24 25 // These are some default imgix parameters to set for each image. It is 26 // recommended to have at least this minimal configuration. 27 defaultImgixParams: { auto: 'format,compress' }, 28 29 // This configures which nodes to modify. 30 fields: [ 31 // Add an object to this array for each node type you want to modify. Follow the instructions below for this. 32 ], 33 }, 34 }, 35 ], 36};
fields
item correctlyIt's necessary to add a configuration for each GraphQL node type you would like to modify. For example, if you have a page which queries both for blog posts, and also blog post categories, you will need to add items for each type separately.
The first step is to find the node type you would like to modify. To do this, look at the GraphQL query for the image you would like to modify. You need to find the node type for the node that image belongs to. For example, for the following query, the node type is ContentfulAsset
, since that is the type of heroImage
. This can be confirmed by copying the query into the GraphiQL editor and hovering over the node type. More detailed instructions on how to find the node types can be found in this section
1query HomeQuery { 2 allContentfulBlogPost { 3 nodes { 4 heroImage { # this is the node to modify 5 fluid {...} 6 } 7 } 8 } 9 10}
Then, you need to configure a field for this node type. The quickest way to configure this is to see if the examples below include a configuration for the node that you would like to transform. If it exists, just copy and paste that into the list of fields
, and you're done. Otherwise, skip to the section for manual setup.
1// ContentfulAsset 2{ 3 nodeType: "ContentfulAsset", 4 fieldName: "imgixImage", 5 rawURLKey: 'file.url', 6 URLPrefix: 'https:', 7},
1{ 2 nodeType: "DatoCmsAsset", 3 rawURLKey: 'entityPayload.attributes.url', 4 fieldName: "imgixImage", 5},
1// Drupal 2{ 3 nodeType: 'File', 4 rawURLKey: (node) => node.url, 5 fieldName: 'imgixImage', 6},
1{ 2 // This is the GraphQL node type that you want to modify. There's 3 // more info on how to find this below. 4 nodeType: '', 5 6 // This is used to pull the raw image URL from the node you want to 7 // transform. The value here should be the path in the node that 8 // contains the image URL to be transformed. 9 // See more information below on how to set this. 10 rawURLKey: 'imageUrlKey', 11 12 // This is the name of imgix field that will be added to the type. 13 fieldName: 'imgixImage', 14},
The rawURLKey
value needs to be the path to the raw image URL in the node data that should be transformed.
The steps to setting this value correctly is:
Set the option to:
1rawURLKey: '';
Inspect the logged output. The plugin will try to find a suitable image url in the node's data for you, and if it successfully finds one, it will output the code to replace the function with in the corresponding error message.
For example, for ContentfulAsset
, it will display the following error message:
1Error when resolving URL value for node type Post. This probably means that 2the rawURLKey function in gatsby-config.js is incorrectly set. Please read this 3project's README for detailed instructions on how to set this correctly. 4 5Potential images were found at these paths: 6 - imageURL 7 Set following configuration options: 8 rawURLKey: 'imageURL' 9 URLPrefix: 'https:'
As we can see, the correct value for the options are
1rawURLKey: 'imageURL', 2URLPrefix: 'https:'
If no value was suggested, you will need to inspect the logged output to find a suitable image URL that corresponds to the image you want to transform. For example, if we're searching ContentfulAsset's data, we see the following output in the console:
1{ 2 // ... 3 file: { 4 url: '//images.ctfassets.net/../.jpg', 5 details: { size: 7316629, image: [Object] }, 6 fileName: 'image.jpg', 7 contentType: 'image/jpeg' 8 }, 9 // ... 10}
Therefore, we need to set the option to file.url
, to return the url at node.file.url
. NB: the value for rawURLKey
is passed to lodash.get
, so array indices, etc can also be used if necessary.
Set the option to the correct value, making sure that the URL includes an http or https. For this example, since the image URL didn't have a https
, we have to add https
to the URLPrefix
option:
1rawURLKey: 'file.url`, 2URLPrefix: 'https:'
The easiest way to find a node's type is to copy the query to the GraphiQL explorer (can be found at localhost:8000/__graphql). Then, while holding Cmd or Ctrl, hover over the node that you are trying to find the type for.
In the screenshot below, we have hovered over the heroImage
field, and we can see the type is ContentfulAsset
. This is the value we can set in the plugin's config.
It's also possible to add __typeName
to the GraphQL query to find the node type. This is useful if you are unable to use the GraphiQL explorer. Here we can see again that the node type is ContentfulAsset
Setting auto: ['format', 'compress']
is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.
This plugin now supports the latest GatsbyImage
component, which delivers better performance and Lighthouse scores, while improving the developer experience.
To use this plugin with GatsbyImage
, the usage is quite similar to the normal usage with gatsby-plugin-image
. This plugin exposes a gatsbyImageData
GraphQL field which is very similar to the native field.
Example:
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3import { GatsbyImage } from 'gatsby-plugin-image'; 4 5export default ({ data }) => { 6 return ( 7 <GatsbyImage 8 image={data.allContentfulAsset.edges[0].node.imgixImage.gatsbyImageData} 9 /> 10 ); 11}; 12 13export const query = gql` 14 { 15 allContentfulAsset { 16 edges { 17 node { 18 imgixImage { 19 gatsbyImageData(width: 400, imgixParams: {}) 20 } 21 } 22 } 23 } 24 } 25`;
The layout
, width
, height
, aspectRatio
, outputPixelDensities
, breakpoints
, sizes
, and backgroundColor
parameters are identical to the parameters offered by the native gatsbyImageData
field, and the documentation for those fields can be found in the Gatsby documentation. The other added parameters are specific to imgix and they are documented in the GraphQL type definitions, which can be explored in GraphiQL (usually at http://localhost:8000/__graphiql)
The following code will render a fluid image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3 4export default ({ data }) => { 5 return ( 6 <Img 7 fluid={{ 8 ...data.allContentfulAsset.edges[0].node.imgixImage.fluid, 9 sizes: '100vw', 10 }} 11 /> 12 ); 13}; 14 15export const query = gql` 16 { 17 allContentfulAsset { 18 edges { 19 node { 20 imgixImage { 21 fluid(imgixParams: { 22 // pass any imgix parameters you want to here 23 }) { 24 ...GatsbyImgixFluid 25 } 26 } 27 } 28 } 29 } 30 } 31`;
A full list of imgix parameters can be found here.
Although sizes
is optional, it is highly recommended. It has a default of (max-width: 8192px) 100vw, 8192px
, which means that it is most likely loading an image too large for your users. Some examples of what you can set sizes as are:
500px
- the image is a fixed width. In this case, you should use fixed mode, described in the next section.(min-width: 1140px) 1140px, 100vw
- under 1140px, the image is as wide as the viewport. Above 1140px, it is fixed to 1140px.The following code will render a fixed image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3 4export default ({ data }) => { 5 return <Img fixed={data.allContentfulAsset.edges[0].node.imgixImage.fixed} />; 6}; 7 8export const query = gql` 9 { 10 allContentfulAsset { 11 edges { 12 node { 13 imgixImage { 14 fixed( 15 width: 960 # Width (in px) is required 16 imgixParams: {} 17 ) { 18 ...GatsbyImgixFixed 19 } 20 } 21 } 22 } 23 } 24 } 25`;
A full list of imgix parameters can be found here.
If you would rather not use gatsby-image and would instead prefer just a plain imgix URL, you can use the url
field to generate one. For instance, you could generate a URL and use it for the background image of an element:
1import gql from 'graphql-tag'; 2 3export default ({ data }) => { 4 return ( 5 <div 6 style={{ 7 backgroundImage: `url(${data.allContentfulAsset.edges[0].node.imgixImage.url})`, 8 backgroundSize: 'contain', 9 width: '100vw', 10 height: 'calc(100vh - 64px)', 11 }} 12 > 13 <h1>Blog Title</h1> 14 </div> 15 ); 16}; 17 18export const query = gql` 19 { 20 allContentfulAsset { 21 edges { 22 node { 23 imgixImage { 24 url(imgixParams: { w: 1200, h: 800 }) 25 } 26 } 27 } 28 } 29 } 30`;
imgixImage
APIThis feature can be best thought about as a replacement for gatsby-image-sharp for images that are statically defined at build time. This allows imgix URLs to be used with gatsby-image through the Gatsby GraphQL API. This feature transforms imgix URLs into a format that is compatible with gatsby-image. This can generate either fluid or fixed images. With this feature you can either display images that already exist on imgix, or proxy other images through imgix.
This feature supports many of the existing gatsby-image GraphQL that you know and love, and also supports most of the features of gatsby-image, such as blur-up and lazy loading. It also brings all of the great features of imgix, including the extensive image transformations and optimisations, as well as the excellent imgix CDN.
This source must be configured in your gatsby-config
file as follows:
1module.exports = { 2 //... 3 plugins: [ 4 // your other plugins here 5 { 6 resolve: `@imgix/gatsby`, 7 options: { 8 domain: '<your imgix domain, e.g. acme.imgix.net>', 9 defaultImgixParams: { auto: ['compress', 'format'] }, 10 }, 11 }, 12 ], 13};
Setting { auto: ['compress', 'format'] }
is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.
This plugin now supports the latest GatsbyImage
component, which delivers better performance and Lighthouse scores, while improving the developer experience.
To use this plugin with GatsbyImage
, the usage is quite similar to the normal usage with gatsby-plugin-image
. This plugin exposes a gatsbyImageData
GraphQL field which is very similar to the native field.
Example:
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3import { GatsbyImage } from 'gatsby-plugin-image'; 4 5export default ({ data }) => { 6 return <GatsbyImage image={data.imgixImage.gatsbyImageData} />; 7}; 8 9export const query = gql` 10 { 11 imgixImage(url: "https://assets.imgix.net/amsterdam.jpg") { 12 gatsbyImageData(width: 400, imgixParams: {}) 13 } 14 } 15`;
The layout
, width
, height
, aspectRatio
, outputPixelDensities
, breakpoints
, sizes
, and backgroundColor
parameters are identical to the parameters offered by the native gatsbyImageData
field, and the documentation for those fields can be found in the Gatsby documentation. The other added parameters are specific to imgix and they are documented in the GraphQL type definitions, which can be explored in GraphiQL (usually at http://localhost:8000/__graphiql)
The following code will render a fluid image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3 4export default ({ data }) => { 5 return <Img fluid={{ ...data.imgixImage.fluid, sizes: '100vw' }} />; 6}; 7 8export const query = gql` 9 { 10 imgixImage(url: "/image.jpg") { 11 fluid(imgixParams: { 12 // pass any imgix parameters you want to here 13 }) { 14 ...GatsbyImgixFluid 15 } 16 } 17 } 18`;
A full list of imgix parameters can be found here.
Although sizes
is optional, it is highly recommended. It has a default of (max-width: 8192px) 100vw, 8192px
, which means that it is most likely loading an image too large for your users. Some examples of what you can set sizes as are:
500px
- the image is a fixed width. In this case, you should use fixed mode, described in the next section.(min-width: 1140px) 1140px, 100vw
- under 1140px, the image is as wide as the viewport. Above 1140px, it is fixed to 1140px.The following code will render a fixed image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3 4export default ({ data }) => { 5 return <Img fixed={data.imgixImage.fixed} />; 6}; 7 8export const query = gql` 9 { 10 imgixImage(url: "/image.jpg") { 11 fixed( 12 width: 960 # Width (in px) is required 13 imgixParams: {} 14 ) { 15 ...GatsbyImgixFixed 16 } 17 } 18 } 19`;
A full list of imgix parameters can be found here.
If you would rather not use gatsby-image and would instead prefer just a plain imgix URL, you can use the url
field to generate one. For instance, you could generate a URL and use it for the background image of an element:
1import gql from 'graphql-tag'; 2 3export default ({ data }) => { 4 return ( 5 <div 6 style={{ 7 backgroundImage: `url(${data.imgixImage.url})`, 8 backgroundSize: 'contain', 9 width: '100vw', 10 height: 'calc(100vh - 64px)', 11 }} 12 > 13 <h1>Blog Title</h1> 14 </div> 15 ); 16}; 17 18export const query = gql` 19 { 20 imgixImage(url: "/image.jpg") { 21 url(imgixParams: { w: 1200, h: 800 }) 22 } 23 } 24`;
If you would like to proxy images from another domain, you should set up a Web Proxy Source. After doing this, you can use this source with this plugin as follows:
gatsby-config.js
to the following:1module.exports = { 2 //... 3 plugins: [ 4 // your other plugins here 5 { 6 resolve: `@imgix/gatsby-source-url`, 7 options: { 8 domain: '<your proxy source domain, e.g. my-proxy-source.imgix.net>', 9 secureURLToken: '...', // <-- now required, your "Token" from your source page 10 defaultImgixParams: ['auto', 'format'], 11 }, 12 }, 13 ], 14};
url
parameter in the GraphQL API. For example, to render a fixed image, a page would look like this:1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3 4export default ({ data }) => { 5 return <Img fixed={data.imgixImage.fixed} />; 6}; 7 8export const query = gql` 9 { 10 imgixImage(url: "https://acme.com/my-image-to-proxy.jpg") { 11 # Now this is a full URL 12 fixed( 13 width: 960 # Width (in px) is required 14 ) { 15 ...GatsbyImgixFixed 16 } 17 } 18 } 19`;
This features allows imgix urls to be used with gatsby-image or gatsby-plugin-image. imgix urls are transformed into a format that is compatible with gatsby-image. This can generate either fluid, fixed images, or for gatsby-plugin-image, full-width, constrained, or fixed images. With this feature you can either display images that already exist on imgix, or proxy other images through imgix. It is important to note that this feature can only display images that are already on imgix or an imgix-compatible URL. To display images that are not using imgix, you will have to use one of the GraphQL APIs above.
⚠️ This means that Web Proxy Sources are not supported with this API. To use Web Proxy Sources, either of the other two APIs must be used.
Unfortunately, due to limitations of Gatsby, this feature does not support blurred placeholders. To use placeholders please use one of the other use cases/parts of this library
This plugin supports the new frontend Gatsby-plugin-image component. To use the component with this plugin, use the following code
1import { ImgixGatsbyImage } from '@imgix/gatsby'; 2 3export const MyPageComponent = () => { 4 return ( 5 <ImgixGatsbyImage 6 // Must be an imgix URL 7 src="https://assets.imgix.net/amsterdam.jpg" 8 // This can be used to set imgix params 9 imgixParams={{ crop: 'faces' }} 10 // These are passed through to the gatsby-plugin-image component 11 layout="constrained" 12 width={768} 13 // Set either 14 aspectRatio={16 / 9} 15 // or 16 sourceWidth={5000} 17 sourceHeight={4000} 18 19 // Any other props offered by the gatsby-plugin-image component are 20 // supported and passed straight through to the component 21 /> 22 ); 23};
If you would like more control over the data flow, you can also use the hook that this package exports - getGatsbyImageData
- like so:
1import { getGatsbyImageData } from '@imgix/gatsby';
2import { GatsbyImage } from 'gatsby-plugin-image';
3
4export const MyPageComponent = () => {
5 return <GatsbyImage
6 image={getGatsbyImageData({
7 // Must be an imgix URL
8 src: "https://assets.imgix.net/amsterdam.jpg"
9 // This can be used to set imgix params
10 imgixParams: { crop: 'faces' }
11
12 // These are passed through to the gatsby-plugin-image component
13 layout: "constrained"
14 width: 768
15
16 // Set either
17 aspectRatio: 16 / 9
18 // or
19 sourceWidth: 5000
20 sourceHeight: 4000
21 })}
22 >
23}
The following code will render a fluid image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.
1import Img from 'gatsby-image';
2import { buildFluidImageData } from '@imgix/gatsby';
3
4// Later, in a gatsby page/component.
5<Img
6 fluid={buildFluidImageData(
7 'https://assets.imgix.net/examples/pione.jpg',
8 {
9 // imgix parameters
10 ar: 1.61, // required
11 auto: ['format', 'compress'], // recommended for all images
12 // pass other imgix parameters here, as needed
13 },
14 {
15 sizes: '50vw', // optional, but highly recommended
16 },
17 )}
18/>;
ar
is required, since gatsby-image requires this to generate placeholders. This ar
will also crop the rendered photo from imgix to the same aspect ratio. If you don't know the aspect ratio of your image beforehand, it is virtually impossible to use gatsby-image in this format, so we either recommend using another of our plugins, or using an img
directly.
Setting auto: ['format', 'compress']
is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.
A full list of imgix parameters can be found here.
Although sizes
is optional, it is highly recommended. It has a default of 100vw
, which means that it might be loading an image too large for your users. Some examples of what you can set sizes as are:
500px
- the image is a fixed width. In this case, you should use fixed mode, described in the next section.(min-width: 1140px) 1140px, 100vw
- under 1140px, the image is as wide as the viewport. Above 1140px, it is fixed to 1140px.A full example of a fluid image in a working Gatsby repo can be found on CodeSandbox.
The following code will render a fixed image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.
1import Img from 'gatsby-image';
2import { buildFixedImageData } from '@imgix/gatsby';
3
4// Later, in a gatsby page/component.
5<Img
6 fixed={buildFixedImageData('https://assets.imgix.net/examples/pione.jpg', {
7 // imgix parameters
8 w: 960, // required
9 h: 540, // required
10 auto: ['format', 'compress'], // recommended for all images
11 // pass other imgix parameters here, as needed
12 })}
13/>;
The imgix parameters w
and h
are required, since these are used by gatsby-image to display a placeholder while the image is loading. Other imgix parameters can be added below the width and height.
Setting auto: ['format', 'compress']
is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.
A full list of imgix parameters can be found here.
An example of this mode in a full working Gatsby repo can be found on CodeSandbox.
The majority of the API for this library can be found by using the GraphiQL inspector (usually at https://localhost:8000/__graphql
).
This library also provides some GraphQL fragments, such as GatsbyImgixFluid
, and GatsbyImgixFluid_noBase64
. The values of these fragments can be found at fragments.js
The plugin options that can be specified in gatsby-config.js
are:
Name | Type | Required | Description |
---|---|---|---|
domain | String | The imgix domain to use for the image URLs. Usually in the format .imgix.net | |
defaultImgixParams | Object | Imgix parameters to use by default for every image. Recommended to set to { auto: ['compress', 'format'] } . | |
disableIxlibParam | Boolean | Set to true to remove the ixlib param from every request. See this section for more information. | |
secureURLToken | String | When specified, this token will be used to sign images. Read more about securing images on the imgix Docs site. |
buildFixedImageData
1function buildFixedImageData(
2 /**
3 * An imgix url to transform, e.g. https://yourdomain.imgix.net/your-image.jpg
4 */
5 url: string,
6 /**
7 * A set of imgix parameters to apply to the image.
8 * Parameters ending in 64 will be base64 encoded.
9 * A full list of imgix parameters can be found here: https://docs.imgix.com/apis/url
10 * Width (w) and height (h) are required.
11 */
12 imgixParams: { w: number; h: number } & IImgixParams,
13 /**
14 * Options that are not imgix parameters.
15 * Optional.
16 */
17 options?: {
18 /**
19 * Disable the ixlib diagnostic param that is added to every url.
20 */
21 includeLibraryParam?: boolean;
22 },
23): {
24 width: number;
25 height: number;
26 src: string;
27 srcSet: string;
28 srcWebp: string;
29 srcSetWebp: string;
30};
buildFluidImageData
1export function buildFluidImageData(
2 /**
3 * An imgix url to transform, e.g. https://yourdomain.imgix.net/your-image.jpg
4 */
5 url: string,
6 /**
7 * A set of imgix parameters to apply to the image.
8 * Parameters ending in 64 will be base64 encoded.
9 * A full list of imgix parameters can be found here: https://docs.imgix.com/apis/url
10 * The aspect ratio (ar) as a float is required.
11 */
12 imgixParams: {
13 /**
14 * The aspect ratio to set for the rendered image and the placeholder.
15 * Format: float or string. For float, it can be calculated with ar = width/height. For a string, it should be in the format w:h.
16 */
17 ar: number | string;
18 } & IImgixParams,
19 /**
20 * Options that are not imgix parameters.
21 * Optional.
22 */
23 options?: {
24 /**
25 * Disable the ixlib diagnostic param that is added to every url.
26 */
27 includeLibraryParam?: boolean;
28 /**
29 * The sizes attribute to set on the underlying image.
30 */
31 sizes?: string;
32 },
33): {
34 aspectRatio: number;
35 src: string;
36 srcSet: string;
37 srcWebp: string;
38 srcSetWebp: string;
39 sizes: string;
40};
This section is for third-party plugin developers of Gatsby plugins and sources that would like to expose the functionality of this library inside their own plugins natively. For example, the Prismic Gatsby plugin uses these APIs to expose fixed
, fluid
, url
, and gatsbyImageData
fields on its images that it exposes in its GraphQL API.
This is the main function that should be used to reuse functionality from this library.
Parameter | Type | Required | Description |
---|---|---|---|
imgixClientOptions | Object | Any extra configuration to pass to new ImgixClient from @imgix/js-core (see here for more information). | |
resolveUrl | (source) => string | undefined | ✔ | A callback to resolve the image URL from the source data provided to the resolver. The source data is provided by the resolver of the type you are adding the image fields too. |
resolveWidth | (source) => number | undefined | This callback can be used to provide the source (uncropped) width of the target image from the source data, if known. The data passed to this callback is the same as is passed to resolveUrl . If this callback is not provided, a network request will be made at build time to resolve this information. | |
resolveHeight | (source) => number | undefined | This callback can be used to provide the source (uncropped) height of the target image from the source data, if known. The data passed to this callback is the same as is passed to resolveUrl . If this callback is not provided, a network request will be made at build time to resolve this information. | |
allowListFields | Array | This can be used to restrict the types and fields generated to avoid creating extra unnecessary types. Possible values: url, fixed, fluid, gatsbyImageData. | |
defaultParams | Object | Default imgix parameters to apply for these images. | |
namespace | String | Prepends the types generated by this library with the supplied namespace to avoid name collisions. It is recommended to set this to something unique to your library so that if your developers import another Gatsby plugin that also this plugin that the names do not collide. | |
cache | GatsbyCache | ✔ | The Gatsby cache provided to Gatsby API hooks |
1// gatsby-node.js
2const imgixGatsby = require('@imgix/gatsby/dist/pluginHelpers');
3
4exports.createSchemaCustomization = async (gatsbyContext, options) => {
5 const imgixTypes = imgixGatsby.createImgixGatsbyTypes({
6 cache: gatsbyContext.cache,
7 resolveUrl: (node) => node.imageURL,
8 resolveWidth: (node) => node.imageSourceWidth,
9 resolveHeight: (node) => node.imageSourceHeight,
10 defaultParams: { auto: 'compress,format' },
11 namespace: 'Imgix',
12 imgixClientOptions: {
13 // domain is required if urls are not already imgix urls. If a domain is provided here, and the image urls are not imgix urls, the the imgix source needs to be a web proxy source, and a secureURLToken token is required (see below).
14 domain: 'my-imgix-domain.imgix.net',
15 // secureURLToken is required if imgix source type is web proxy, or "secure URLs" is enabled in the imgix configuration dashboard
16 secureURLToken: 'my-secure-url-token',
17 },
18 });
19
20 const myNodeType = gatsbyContext.schema.buildObject({
21 name: 'MyPluginNodeType',
22 fields: {
23 // Your other node fields, e.g. title, description, etc
24 title: { type: 'String!' },
25
26 // Add the fields returned from createImgixGatsbyTypes to your node as fields
27 imageUrl: imgixTypes.fields.url,
28 fluid: imgixTypes.fields.fluid,
29 fixed: imgixTypes.fields.fixed,
30 gatsbyImageData: imgixTypes.fields.gatsbyImageData,
31 },
32 });
33
34 gatsbyContext.actions.createTypes([
35 ...imgixTypes.types.map(gatsbyContext.schema.buildObjectType),
36 ...imgixTypes.enumTypes.map(gatsbyContext.schema.buildEnumType),
37 ...imgixTypes.inputTypes.map(gatsbyContext.schema.buildInputObjectType),
38 ]);
39 gatsbyContext.actions.createTypes(myNodeType);
40};
These low-level functions can be used to build data that can be passed straight to gatsby-image, or gatsby-plugin-image, if necessary. It is recommended to use createImgixGatsbyTypes
instead of these functions.
buildFluidObject
1import { buildFluidObject } from '@imgix/gatsby/dist/pluginHelpers';
2import Img from 'gatsby-image';
3
4const fluidData = buildFluidObject({
5 // Image url, required. See note in section 'Note about url and imgixClientOptions' about what to do based on what kind of url this is
6 url: 'https://domain.imgix.net/amsterdam.jpg',
7 // Any extra configuration to pass to new ImgixClient from @imgix/js-core (see [here](https://github.com/imgix/js-core#configuration) for more information)
8 imgixClientOptions: {
9 domain: 'domain.imgix.net',
10 secureURLToken: 'secure-token',
11 },
12 // Mimicking GraphQL field args
13 args: {
14 // Imgix params, required (at least {})
15 imgixParams: {},
16 // Imgix params for the placeholder image, required (at least {})
17 placeholderImgixParams: {},
18 // Max image width srcset to generate, required.
19 maxWidth: 8192,
20 // Max image height to generate, optional.
21 maxHeight: 5000,
22 // Custom src set breakpoints to set, optional.
23 srcSetBreakpoints: [100, 200],
24 },
25 // The height in px of the original image, required
26 sourceHeight: 3000,
27 // The width in px of the original image, required
28 sourceWidth: 4000,
29 // Default params to set, required
30 defaultParams: {},
31 // Default placeholder params to set, required
32 defaultPlaceholderParams: {},
33});
34
35// In component later...
36<Img fluid={fluid} />;
buildFixedObject
1import { buildFixedObject } from '@imgix/gatsby/dist/pluginHelpers';
2import Img from 'gatsby-image';
3
4const fixedData = buildFixedObject({
5 // Image url, required. See note in section 'Note about url and imgixClientOptions' about what to do based on what kind of url this is
6 url: 'https://domain.imgix.net/amsterdam.jpg',
7 // Any extra configuration to pass to new ImgixClient from @imgix/js-core (see [here](https://github.com/imgix/js-core#configuration) for more information)
8 imgixClientOptions: {
9 domain: 'domain.imgix.net',
10 secureURLToken: 'secure-token',
11 },
12 // Mimicking GraphQL field args
13 args: {
14 // Imgix params, required (at least {})
15 imgixParams: {},
16 // Imgix params for the placeholder image, required (at least {})
17 placeholderImgixParams: {},
18 // The width of the image in px for the 1x image, required.
19 width: 100,
20 // The height of the image in px for the 1x image, optional
21 height: 200,
22 // The imgix quality param to set, optional.
23 quality: 50,
24 },
25 // The height in px of the original image, required
26 sourceHeight: 3000,
27 // The width in px of the original image, required
28 sourceWidth: 4000,
29 // Default params to set, required
30 defaultParams: {},
31 // Default placeholder params to set, required
32 defaultPlaceholderParams: {},
33});
34
35// In component later...
36<Img fixed={fixed} />;
buildGatsbyImageDataObject
1import { buildGatsbyImageDataObject } from '@imgix/gatsby/dist/pluginHelpers';
2import { GatsbyImage } from 'gatsby-plugin-image';
3
4const gatsbyImageData = buildGatsbyImageDataObject({
5 // Image url, required. See note in section 'Note about url and imgixClientOptions' about what to do based on what kind of url this is
6 url: 'https://domain.imgix.net/amsterdam.jpg',
7 // Any extra configuration to pass to new ImgixClient from @imgix/js-core (see [here](https://github.com/imgix/js-core#configuration) for more information)
8 imgixClientOptions: {
9 domain: 'domain.imgix.net',
10 secureURLToken: 'secure-token',
11 },
12 // Mimicking GraphQL field args
13 resolverArgs: {
14 // The gatsby-plugin-image layout parameter
15 layout: 'fullWidth',
16 // Imgix params, optional
17 imgixParams: {},
18 // Imgix params for the placeholder image, optional
19 placeholderImgixParams: {},
20 // The width or max-width (depending on the layout setting) of the image in px, optional.
21 width: 100,
22 // The height or max-height (depending on the layout setting) of the image in px, optional.
23 height: 200,
24 // The aspect ratio of the srcsets to generate, optional
25 aspectRatio: 2,
26 // Custom srcset breakpoints to use, optional
27 breakpoints: [100, 200],
28 // Custom 'sizes' attribute to set, optional
29 sizes: '100vw',
30 // Custom srcset max width, optional
31 srcSetMaxWidth: 8000,
32 // Custom srcset min width, optional
33 srcSetMinWidth: 100,
34 // The factor used to scale the srcsets up, optional.
35 // E.g. if srcsetMinWidth is 100, then the srcsets are generated as follows
36 // while (width < maxWidth) nextSrcSet = prevSrcSet * (1 + widthTolerance)
37 widthTolerance: 0.08,
38 },
39 // source width and of the uncropped image
40 dimensions: { width: 5000, height: 3000 },
41});
42
43<GatsbyImage image={gatsbyImageData} />;
Depending on what kind of image URL url
is set to in the above object helpers, domain
and secureURLToken
might have to be passed in imgixClientOptions
.
If url
is:
domain
and secureURLToken
are likely not required. If domain
is set, the source must be a Web Proxy Source. If "secure URLs" are enabled on the imgix source, or the source is a Web Proxy Source, secureURLToken
is required./image.jpg
), domain
is required, and the domain should point to an imgix S3, GCP, Azure, or Web Folder source. secureURLToken
is only required if "secure URLs" are enabled on the imgix source.domain
and secureURLToken
are required, and domain
should point to a Web Proxy imgix source.ixlib
Param on Every Request?For security and diagnostic purposes, we tag all requests with the language and version of the library used to generate the URL. To disable this, we provide two options.
For disabling the ixlib
parameter across all requests, we provide disableIxlibParam
as a plugin option for use in gatsby-config.js
.
1// gatsby-config.js 2module.exports = { 3 //... 4 plugins: [ 5 // your other plugins here 6 { 7 resolve: `@imgix/gatsby`, 8 options: { 9 domain: '<domain.imgix.net>', 10 disableIxlibParam: 'true', // this disables the ixlib parameter 11 defaultImgixParams: { auto: ['compress', 'format'] }, 12 }, 13 }, 14 ], 15};
For disabling ixlib
on a case by case basis, we provide the includeLibraryParam
parameter. When calling either of this library's two exported functions, in the third parameter set includeLibraryParam
to false
. For example, for buildFluidImageData
:
1<Img
2 fluid={buildFixedImageData(
3 'https://assets.imgix.net/examples/pione.jpg',
4 {
5 w: 960,
6 h: 540,
7 },
8 {
9 includeLibraryParam: false, // this disables the ixlib parameter
10 },
11 )}
12/>
@imgix/gatsby customizes existing GraphQl types in order to expose our own types on those same fields. This allows for a more seamless integration with Gatsby. It also means that you might see a warning like this:
1warn Plugin `@imgix/gatsby` has customized the GraphQL type `ShopifyCollectionImage`, which has already been defined by the plugin `gatsby-source-shopify`. This could potentially cause conflicts.
This warning can be safely ignored, ie this should not impact your build in any way.
This warning stems from the fact that type inference is "not allowed" in Gatsby plugins. In other words, Gatsby assumes that plugins are not modifying types that they do not own. Therefore it logs a warning whenever types are modified by a plugin that did not create them.
Gatsby does this in an effort to reduce the likelihood installing one plugin can break an entire build. If one plugin can change any plugin's type, it can break any plugin in the build. gatsby-imgix only modifies types that the user explicitly denotes as their image types. So we don't run the risk of overwriting or modifying types outside a source's explicitly denoted image types.
You can read more about this if you’re interested in this issue.
You might find yourself with multiple imgix sources and wondering how you could use them at the same time with this plugin. There are a few possibilities for this, which will be outlined below.
Any number of sources can be used simultaneously with the URL transform API.
Example:
1import { ImgixGatsbyImage } from '@imgix/gatsby'; 2 3export const MyPageComponent = () => ( 4 <div> 5 <ImgixGatsbyImage src="https://first-source.imgix.net/image.jpg" /> 6 <ImgixGatsbyImage src="https://second-source.imgix.net/image.jpg" /> 7 </div> 8);
The caveats with this approach is that you don't get the benefits of the GraphQL APIs (blur-up, etc), and that the sources must not be Web Proxy sources (for these you must use one of the GraphQL APIs).
Additionally, a source can be configured for one of the GraphQL APIs, and this source can be a Web Proxy source. Thus seemingly you could combine one of the GraphQL APIs and the URL transform API together to use multiple sources this way:
1import gql from 'graphql-tag'; 2import Img from 'gatsby-image'; 3import { GatsbyImage } from 'gatsby-plugin-image'; 4import { ImgixGatsbyImage } from '@imgix/gatsby'; 5 6export default ({ data }) => ( 7 <div> 8 <GatsbyImage image={data.imgixImage.gatsbyImageData} />; 9 <ImgixGatsbyImage src="https://second-source.imgix.net/image.jpg" /> 10 </div> 11); 12 13export const query = gql` 14 { 15 imgixImage(url: "https://assets.imgix.net/amsterdam.jpg") { 16 gatsbyImageData(width: 400, imgixParams: {}) 17 } 18 } 19`;
So, to summarise, it is possible to use multiple sources in this plugin. You have the option to use up to one source of any type with the GraphQL API, and then any number of non-Web Proxy sources with the URL transform API.
Between v1 and v2, the method to retrieve the image url in the GraphQL from the raw data was changed. This was done to support Gatsby v4, as function configuration options are no longer possible in Gatsby v4. If you do not use the GraphQL transform API, then you do not have to change anything.
To upgrade from v1 to v2, the following configuration options need to be updated:
1// gatsby-config.js 2module.exports = { 3 plugins: { 4 // ... 5 { 6 resolve: `@imgix/gatsby`, 7 options: { 8 // ... 9 fields: [ 10 { 11 nodeType: "Post", 12 fieldName: "imgixImage", 13 14 // The follow option needs to be changed... 15 getURL: node => `https:${node.banner.imageURL}`, 16 17 // to this: 18 rawURLKey: "banner.imageURL", 19 URLPrefix: "https:", 20 }, 21 ], 22 }, 23 }, 24 } 25}
@imgix/gatsby-transform-url
@imgix/gatsby-transform-url
was deprecated in favor of combining these sub-projects into one single project, for simplicity.
The functionality of that library can be found, unchanged, under this new package. Specifically, all that needs to changed is the import statements, e.g. from
1import { buildFluidImageData } from '@imgix/gatsby-transform-url';
to
1import { buildFluidImageData } from '@imgix/gatsby';
Contributions are a vital part of this library and imgix's commitment to open-source. We welcome all contributions which align with this project's goals. More information can be found in the contributing documentation.
imgix would like to make a special announcement about the prior work of Angelo Ashmore from Wall-to-Wall Studios on his gatsby plugin for imgix. The code and API from his plugin has made a significant contribution to the codebase and API for imgix's official plugins, and imgix is very grateful that he agreed to collaborate with us.
Thanks goes to these wonderful people (emoji key):
Frederick Fogerty 💻 📖 🚧 | Angelo Ashmore 💻 | Luis H. Ball Jr. 📖 | Sherwin Heydarbeygi 📖 |
This project follows the all-contributors specification.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 2/14 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
77 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More