Gathering detailed insights and metrics for imagekit
Gathering detailed insights and metrics for imagekit
Gathering detailed insights and metrics for imagekit
Gathering detailed insights and metrics for imagekit
npm install imagekit
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
85 Stars
285 Commits
32 Forks
8 Watching
21 Branches
17 Contributors
Updated on 05 Nov 2024
JavaScript (52.81%)
TypeScript (46.85%)
Shell (0.34%)
Cumulative downloads
Total Downloads
Last day
-13.2%
1,435
Compared to previous day
Last week
-4.8%
9,752
Compared to previous week
Last month
15.9%
45,150
Compared to previous month
Last year
-1.3%
443,462
Compared to previous year
Node.js SDK for ImageKit implements the new APIs and interface for different file operations.
ImageKit is complete media storage, optimization, and transformation solution that comes with an image and video CDN. It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes.
1. Overlay syntax update
oi
, ot
, obg
, and more. These parameters are deprecated and will start returning errors when used in URLs. Please migrate to the new layers syntax that supports overlay nesting, provides better positional control, and allows more transformations at the layer level. You can start with examples to learn quickly.raw
transformation parameter.2. Remove Node.js 10.x support
Use the following command to download this module. Use the optional --save
parameter if you wish to save the dependency in your package.json
file.
npm install imagekit --save
# or
yarn add imagekit
1import ImageKit from "imagekit"; 2 3// or 4 5var ImageKit = require("imagekit"); 6 7var imagekit = new ImageKit({ 8 publicKey : "your_public_api_key", 9 privateKey : "your_private_api_key", 10 urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" 11});
You can use this Node.js SDK for three different methods - URL generation, file upload, and media management operations. The usage of the SDK has been explained below.
URL Generation
File Upload
File Management
1. Using image path and image hostname or endpoint
This method allows you to create an URL to access a file using the relative file path and the ImageKit URL endpoint (urlEndpoint
). The file can be an image, video or any other static file supported by ImageKit.
1// For URL Generation, works for both images and videos 2var imageURL = imagekit.url({ 3 path : "/default-image.jpg", 4 urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/endpoint/", 5 transformation : [{ 6 "height" : "300", 7 "width" : "400" 8 }] 9});
This results in a URL like
https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jpg
2. Using full image URL
This method allows you to add transformation parameters to an absolute URL. For example, if you have configured a custom CNAME and have absolute asset URLs in your database or CMS, you will often need this.
1var imageURL = imagekit.url({ 2 src : "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", 3 transformation : [{ 4 "height" : "300", 5 "width" : "400" 6 }] 7});
This results in a URL like
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400
The .url()
method accepts the following parameters
Option | Description |
---|---|
urlEndpoint | Optional. The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/ |
path | Conditional. This is the path at which the image exists. For example, /path/to/image.jpg . Either the path or src parameter needs to be specified for URL generation. |
src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg . Either the path or src parameter needs to be specified for URL generation. |
transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a chained transformation can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. |
transformationPosition | Optional. The default value is path that places the transformation string as a path parameter in the URL. It can also be specified as query , which adds the transformation string as the URL's query parameter tr . If you use the src parameter to create the URL, then the transformation string is always added as a query parameter. |
queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameter to your URLs. |
signed | Optional. Boolean. Default is false . If set to true , the SDK generates a signed image URL adding the image signature to the image URL. If you create a URL using the src parameter instead of path , then do correct urlEndpoint for this to work. Otherwise returned URL will have the wrong signature |
expireSeconds | Optional. Integer. Meant to be used along with the signed parameter to specify the time in seconds from now when the URL should expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly. |
1. Chained Transformations as a query parameter
1var imageURL = imagekit.url({ 2 path : "/default-image.jpg", 3 urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/endpoint/", 4 transformation : [{ 5 "height" : "300", 6 "width" : "400" 7 }, { 8 "rotation" : 90 9 }], 10 transformationPosition : "query" 11});
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400%3Art-90
2. Sharpening and contrast transforms and a progressive JPG image
There are some transforms like Sharpening that can be added to the URL with or without any other value. To use such transforms without specifying a value, specify the value as "-" in the transformation object. Otherwise, specify the value that you want to be added to this transformation.
1var imageURL = imagekit.url({ 2 src : "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", 3 transformation : [{ 4 "format" : "jpg", 5 "progressive" : "true", 6 "effectSharpen" : "-", 7 "effectContrast" : "1" 8 }] 9});
//Note that because the `src` parameter was used, the transformation string gets added as a query parameter `tr`
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=f-jpg%2Cpr-true%2Ce-sharpen%2Ce-contrast-1
3. Signed URL that expires in 300 seconds with the default URL endpoint and other query parameters
1var imageURL = imagekit.url({ 2 path : "/default-image.jpg", 3 queryParameters : { 4 "v" : "123" 5 }, 6 transformation : [{ 7 "height" : "300", 8 "width" : "400" 9 }], 10 signed : true, 11 expireSeconds : 300 12});
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400/default-image.jpg?v=123&ik-t=1567358667&ik-s=f2c7cdacbe7707b71a83d49cf1c6110e3d701054
4. Adding overlays
ImageKit.io enables you to apply overlays to images and videos using the raw parameter with the concept of layers. The raw parameter facilitates incorporating transformations directly in the URL. A layer is a distinct type of transformation that allows you to define an asset to serve as an overlay, along with its positioning and additional transformations.
Text as overlays
You can add any text string over a base video or image using a text layer (l-text).
For example:
1var imageURL = imagekit.url({ 2 src: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", 3 transformation: [{ 4 "width": 400, 5 "height": 300 6 "raw": "l-text,i-Imagekit,fs-50,l-end" 7 }] 8});
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-text,i-Imagekit,fs-50,l-end/default-image.jpg
Image as overlays
You can add an image over a base video or image using an image layer (l-image).
For example:
1var imageURL = imagekit.url({ 2 src: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", 3 transformation: [{ 4 "width": 400, 5 "height": 300 6 "raw": "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end" 7 }] 8});
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end/default-image.jpg
Solid color blocks as overlays
You can add solid color blocks over a base video or image using an image layer (l-image).
For example:
1var imageURL = imagekit.url({ 2 src: "https://ik.imagekit.io/your_imagekit_id/img/sample-video.mp4", 3 transformation: [{ 4 "width": 400, 5 "height": 300 6 "raw": "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end" 7 }] 8});
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end/img/sample-video.mp4
5. Arithmetic expressions in transformations
ImageKit allows use of arithmetic expressions in certain dimension and position-related parameters, making media transformations more flexible and dynamic.
For example:
1var imageURL = imagekit.url({ 2 src: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", 3 transformation: [{ 4 "width": "iw_div_4", 5 "height": "ih_div_2", 6 "border": "cw_mul_0.05_yellow" 7 }] 8});
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:w-iw_div_4,h-ih_div_2,b-cw_mul_0.05_yellow/default-image.jpg
See the complete list of transformations supported in ImageKit here. The SDK gives a name to each transformation parameter e.g. height
for h
and width
for w
parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is.
If you want to generate transformations in your application and add them to the URL as it is, use the raw
parameter.
Supported Transformation Name | Translates to parameter |
---|---|
height | h |
width | w |
aspectRatio | ar |
quality | q |
crop | c |
cropMode | cm |
x | x |
y | y |
focus | fo |
format | f |
radius | r |
background | bg |
border | b |
rotation | rt |
blur | bl |
named | n |
progressive | pr |
lossless | lo |
trim | t |
metadata | md |
colorProfile | cp |
defaultImage | di |
dpr | dpr |
effectSharpen | e-sharpen |
effectUSM | e-usm |
effectContrast | e-contrast |
effectGray | e-grayscale |
effectShadow | e-shadow |
effectGradient | e-gradient |
original | orig |
raw | replaced by the parameter value |
The SDK provides a simple interface using the .upload()
method to upload files to the ImageKit Media Library. It accepts all the parameters supported by the ImageKit Upload API.
The upload()
method requires at least the file
and the fileName
parameter to upload a file and returns a callback with the error
and result
as arguments. You can pass other parameters supported by the ImageKit upload API using the same parameter name as specified in the upload API documentation. For example, to set tags for a file at the upload time, use the tags
parameter as defined in the documentation here.
Sample usage
1// Using Callback Function 2 3imagekit.upload({ 4 file : <url|base_64|binary>, //required 5 fileName : "my_file_name.jpg", //required 6 extensions: [ 7 { 8 name: "google-auto-tagging", 9 maxTags: 5, 10 minConfidence: 95 11 } 12 ], 13 transformation: { 14 pre: 'l-text,i-Imagekit,fs-50,l-end', 15 post: [ 16 { 17 type: 'transformation', 18 value: 'w-100' 19 } 20 ] 21 }, 22 checks: {`"file.size" < "1mb"`}, // To run server side checks before uploading files. Notice the quotes around file.size and 1mb. 23 isPublished: true 24}, function(error, result) { 25 if(error) console.log(error); 26 else console.log(result); 27}); 28 29// Using Promises 30 31imagekit.upload({ 32 file : <url|base_64|binary>, //required 33 fileName : "my_file_name.jpg", //required 34 extensions: [ 35 { 36 name: "google-auto-tagging", 37 maxTags: 5, 38 minConfidence: 95 39 } 40 ], 41 transformation: { 42 pre: 'l-text,i-Imagekit,fs-50,l-end', 43 post: [ 44 { 45 type: 'transformation', 46 value: 'w-100' 47 } 48 ] 49 }, 50 checks={`"file.size" < "1mb"`} 51}).then(response => { 52 console.log(response); 53}).catch(error => { 54 console.log(error); 55});
If the upload succeeds, error
will be null,
and the result
will be the same as what is received from ImageKit's servers.
If the upload fails, the error
will be the same as what is received from ImageKit's servers, and the result
will be null.
The SDK provides a simple interface for all the media APIs mentioned here to manage your files. You can use a callback function with all API interfaces. The first argument of the callback function is the error, and the second is the result of the API call. The error will be null
if the API succeeds.
List & Search Files
Accepts an object specifying the parameters used to list and search files. All parameters specified in the documentation here can be passed as-is with the correct values to get the results.
1// Using Callback Function
2
3imagekit.listFiles({
4 skip : 10,
5 limit : 10
6}, function(error, result) {
7 if(error) console.log(error);
8 else console.log(result);
9});
10
11
12// Using Promises
13
14imagekit.listFiles({
15 skip : 10,
16 limit : 10
17}).then(response => {
18 console.log(response);
19}).catch(error => {
20 console.log(error);
21});
Get File Details
Accepts the file ID and fetches the details as per the API documentation here.
1// Using Callback Function
2
3imagekit.getFileDetails("file_id", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8
9// Using Promises
10
11imagekit.getFileDetails("file_id")
12}).then(response => {
13 console.log(response);
14}).catch(error => {
15 console.log(error);
16});
Get File Versions
Accepts the file ID and fetches all the versions of that file as per the API documentation here.
1// Using Callback Function
2
3imagekit.getFileVersions("file_id", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8
9// Using Promises
10
11imagekit.getFileVersions("file_id")
12}).then(response => {
13 console.log(response);
14}).catch(error => {
15 console.log(error);
16});
Get File version details
Accepts the file ID & version ID and returns the details of that specific version as per the API documentation here.
1// Using Callback Function 2 3imagekit.getFileVersionDetails({ 4 fileId: "file_id", 5 versionId: "version_id" 6}, function(error, result) { 7 if(error) console.log(error); 8 else console.log(result); 9}); 10 11 12// Using Promises 13 14imagekit.getFileVersionDetails({ 15 fileId: "file_id", 16 versionId: "version_id" 17}) 18}).then(response => { 19 console.log(response); 20}).catch(error => { 21 console.log(error); 22});
Update File Details
Update parameters associated with the file as per the API documentation here. The first argument to the updateFileDetails
method is the file ID, and the second argument is an object with the parameters to be updated.
Note: If publish
is included in the update options, no other parameters are allowed. If any are present, an error will be returned: Your request cannot contain any other parameters when publish is present
.
1// Using Callback Function 2 3imagekit.updateFileDetails("file_id", { 4 tags : ['image_tag'], 5 customCoordinates : "10,10,100,100", 6 extensions: [ 7 { 8 name: "google-auto-tagging", 9 maxTags: 5, 10 minConfidence: 95 11 } 12 ] 13}, function(error, result) { 14 if(error) console.log(error); 15 else console.log(result); 16}); 17 18 19// Using Promises 20 21imagekit.updateFileDetails("file_id", { 22 publish: { 23 isPublished: true, 24 includeFileVersions: true 25 } 26}).then(response => { 27 console.log(response); 28}).catch(error => { 29 console.log(error); 30});
Bulk Add tags
Add tags to multiple files in a single request as per API documentation here. The method accepts an array of fileIDs of the files and an array of tags that have to be added to those files.
1// Using Callback Function 2 3imagekit.bulkAddTags(["file_id_1", "file_id_2"], ["tag1", "tag2"], function(error, result) { 4 if(error) console.log(error); 5 else console.log(result); 6}); 7 8// Using Promises 9 10imagekit.bulkAddTags(["file_id_1", "file_id_2"], ["tag1", "tag2"]).then(response => { 11 console.log(response); 12}).catch(error => { 13 console.log(error); 14});
Bulk Remove tags
Remove tags from multiple files in a single request as per API documentation here. The method accepts an array of fileIDs of the files and an array of tags that have to be removed from those files.
1// Using Callback Function 2 3imagekit.bulkRemoveTags(["file_id_1", "file_id_2"], ["tags"], function(error, result) { 4 if(error) console.log(error); 5 else console.log(result); 6}); 7 8// Using Promises 9 10imagekit.bulkRemoveTags(["file_id_1", "file_id_2"], ["tags"]).then(response => { 11 console.log(response); 12}).catch(error => { 13 console.log(error); 14});
Bulk Remove AI Tags
Remove AI tags from multiple files in a single request as per API documentation here. The method accepts an array of fileIDs of the files and an array of tags that have to be removed from those files.
1// Using Callback Function 2 3imagekit.bulkRemoveAITags(["file_id_1", "file_id_2"], ["ai-tag1", "ai-tag2"], function(error, result) { 4 if(error) console.log(error); 5 else console.log(result); 6}); 7 8// Using Promises 9 10imagekit.bulkRemoveAITags(["file_id_1", "file_id_2"], ["ai-tag1", "ai-tag2"]).then(response => { 11 console.log(response); 12}).catch(error => { 13 console.log(error); 14});
Delete File
Delete a file as per the API documentation here. The method accepts the file ID of the file that has to be deleted.
1// Using Callback Function
2
3imagekit.deleteFile("file_id", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8
9// Using Promises
10
11imagekit.deleteFile("file_id").then(response => {
12 console.log(response);
13}).catch(error => {
14 console.log(error);
15});
Delete File Version
Delete any non-current version of a file as per the API documentation here.
1// Using Callback Function 2 3imagekit.deleteFileVersion({ 4 fileId: "file_id", 5 versionId: "version_id", 6}, function(error, result) { 7 if(error) console.log(error); 8 else console.log(result); 9}); 10 11 12// Using Promises 13 14imagekit.deleteFile({ 15 fileId: "file_id", 16 versionId: "version_id", 17}).then(response => { 18 console.log(response); 19}).catch(error => { 20 console.log(error); 21});
Bulk Delete Files
Delete multiple files as per the API documentation here. The method accepts an array of file IDs of the files that have to be deleted.
1// Using Callback Function 2 3imagekit.bulkDeleteFiles(["file_id_1", "file_id_2"], function(error, result) { 4 if(error) console.log(error); 5 else console.log(result); 6}); 7 8 9// Using Promises 10 11imagekit.bulkDeleteFiles(["file_id_1", "file_id_2"]).then(response => { 12 console.log(response); 13}).catch(error => { 14 console.log(error); 15});
Copy File
This will copy a file from one location to another as per API documentation here.
1// Using Callback Function
2
3imagekit.copyFile({
4 sourceFilePath: "/path/to/file.jpg",
5 destinationPath: "/folder/to/copy/into/"
6 includeFileVersions: false // optional
7}, function(error, result) {
8 if(error) console.log(error);
9 else console.log(result);
10});
11
12// Using Promises
13
14imagekit.copyFile({
15 sourceFilePath: "/path/to/file.jpg",
16 destinationPath: "/folder/to/copy/into/",
17 includeFileVersions: false // optional
18}).then(response => {
19 console.log(response);
20}).catch(error => {
21 console.log(error);
22});
Move File
This will move a file from one location to another as per API documentation here.
1// Using Callback Function 2 3imagekit.moveFile({ 4 sourceFilePath: "/path/to/file.jpg", 5 destinationPath: "/folder/to/copy/into/", 6}, function(error, result) { 7 if(error) console.log(error); 8 else console.log(result); 9}); 10 11// Using Promises 12 13imagekit.moveFile({ 14 sourceFilePath: "/path/to/file.jpg", 15 destinationPath: "/folder/to/copy/into/", 16}).then(response => { 17 console.log(response); 18}).catch(error => { 19 console.log(error); 20});
Rename File
Rename the file as per API documentation here.
1// Using Callback Function
2
3imagekit.renameFile({
4 filePath: "/path/to/old-file-name.jpg",
5 newFileName: "new-file-name.jpg",
6 purgeCache: false // optional
7}, function(error, result) {
8 if(error) console.log(error);
9 else console.log(result);
10});
11
12// Using Promises
13
14imagekit.renameFile({
15 filePath: "/path/to/old-file-name.jpg",
16 newFileName: "new-file-name.jpg",
17 purgeCache: false // optional
18}).then(response => {
19 console.log(response);
20}).catch(error => {
21 console.log(error);
22});
Restore File Version
Restore the file version as per API documentation here.
1// Using Callback Function 2 3imagekit.restoreFileVersion({ 4 fileId: "file_id", 5 versionId: "version_id" 6}, function(error, result) { 7 if(error) console.log(error); 8 else console.log(result); 9}); 10 11// Using Promises 12 13imagekit.restoreFileVersion({ 14 fileId: "file_id", 15 versionId: "version_id" 16}).then(response => { 17 console.log(response); 18}).catch(error => { 19 console.log(error); 20});
Create Folder
This will create a new folder as per API documentation here.
1// Using Callback Function 2 3imagekit.createFolder({ 4 folderName: "new_folder", 5 parentFolderPath: "source/folder/path" 6}, function(error, result) { 7 if(error) console.log(error); 8 else console.log(result); 9}); 10 11// Using Promises 12 13imagekit.createFolder({ 14 folderName: "new_folder", 15 parentFolderPath: "source/folder/path" 16}).then(response => { 17 console.log(response); 18}).catch(error => { 19 console.log(error); 20});
Delete Folder
This will delete the specified Folder and all nested files & folders as per API documentation here.
1// Using Callback Function
2
3imagekit.deleteFolder("folderPath", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8// Using Promises
9
10imagekit.deleteFolder("folderPath").then(response => {
11 console.log(response);
12}).catch(error => {
13 console.log(error);
14});
Copy Folder
This will copy one Folder into another as per API documentation here.
1// Using Callback Function
2
3imagekit.copyFolder({
4 sourceFolderPath: "/folder/to/copy",
5 destinationPath: "/folder/to/copy/into/",
6 includeFileVersions: false // optional
7}, function(error, result) {
8 if(error) console.log(error);
9 else console.log(result);
10});
11
12// Using Promises
13
14imagekit.copyFolder({
15 sourceFolderPath: "/folder/to/copy",
16 destinationPath: "/folder/to/copy/into/",
17 includeFileVersions: false // optional
18}).then(response => {
19 console.log(response);
20}).catch(error => {
21 console.log(error);
22});
Move Folder
This will move one Folder into another as per API documentation here.
1// Using Callback Function 2 3imagekit.moveFolder({ 4 sourceFolderPath: "/folder/to/move", 5 destinationPath: "/folder/to/move/into/" 6}, function(error, result) { 7 if(error) console.log(error); 8 else console.log(result); 9}); 10 11// Using Promises 12 13imagekit.moveFolder({ 14 sourceFolderPath: "/folder/to/move", 15 destinationPath: "/folder/to/move/into/" 16}).then(response => { 17 console.log(response); 18}).catch(error => { 19 console.log(error); 20});
Get bulk job status
This allows us to get a bulk operation status e.g. copy or move Folder as per API documentation here. This method accepts jobId
that is returned by copy and move folder operations.
1// Using Callback Function
2
3imagekit.getBulkJobStatus("jobId", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8// Using Promises
9
10imagekit.getBulkJobStatus("jobId").then(response => {
11 console.log(response);
12}).catch(error => {
13 console.log(error);
14});
Purge Cache
Programmatically issue a clear cache request as per the API documentation here. Accepts the full URL of the file for which the cache has to be cleared.
1// Using Callback Function
2
3imagekit.purgeCache("full_url", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8
9// Using Promises
10
11imagekit.purgeCache("full_url").then(response => {
12 console.log(response);
13}).catch(error => {
14 console.log(error);
15});
Purge Cache Status
Get the purge cache request status using the request ID returned when a purge cache request gets submitted as per the API documentation here
1// Using Callback Function
2
3imagekit.getPurgeCacheStatus("cache_request_id", function(error, result) {
4 if(error) console.log(error);
5 else console.log(result);
6});
7
8
9// Using Promises
10
11imagekit.getPurgeCacheStatus("cache_request_id").then(response => {
12 console.log(response);
13}).catch(error => {
14 console.log(error);
15});
Get File Metadata
Accepts the file ID and fetches the metadata as per the API documentation here.
1// Using Callback Function
2imagekit.getFileMetadata("file_id", function(error, result) {
3 if(error) console.log(error);
4 else console.log(result);
5});
6
7
8// Using Promises
9imagekit.getFileMetadata("file_id")
10}).then(response => {
11 console.log(response);
12}).catch(error => {
13 console.log(error);
14});
You can also pass the remote URL of the image to get metadata.
1// Using Callback Function
2imagekit.getFileMetadata("https://ik.imagekit.io/your_imagekit_id/sample.jpg", function(error, result) {
3 if(error) console.log(error);
4 else console.log(result);
5});
6
7
8// Using Promises
9imagekit.getFileMetadata("https://ik.imagekit.io/your_imagekit_id/sample.jpg")
10}).then(response => {
11 console.log(response);
12}).catch(error => {
13 console.log(error);
14});
Create a custom metadata field
Create a new custom metadata field as per the API documentation here
1// Using Callback Function 2 3imagekit.createCustomMetadataField( 4 { 5 name: "price", 6 label: "price", 7 schema: { 8 type: "Number", 9 minValue: 1000, 10 maxValue: 3000 11 } 12 }, 13 function(error, result) { 14 if(error) console.log(error); 15 else console.log(result); 16 } 17); 18 19 20// Using Promises 21 22imagekit.createCustomMetadataField( 23 { 24 name: "price", 25 label: "price", 26 schema: { 27 type: "Number", 28 minValue: 1000, 29 maxValue: 3000 30 } 31 } 32).then(response => { 33 console.log(response); 34}).catch(error => { 35 console.log(error); 36});
Get all custom metadata fields
Get the list of all custom metadata fields as per the API documentation here
1// Using Callback Function 2 3imagekit.getCustomMetadataFields( 4 { 5 includeDeleted: false // optional 6 }, 7 function(error, result) { 8 if(error) console.log(error); 9 else console.log(result); 10 } 11); 12 13 14// Using Promises 15 16imagekit.getCustomMetadataFields( 17 { 18 includeDeleted: false // optional 19 } 20).then(response => { 21 console.log(response); 22}).catch(error => { 23 console.log(error); 24});
Update a custom metadata field
Update a custom metadata field as per the API documentation here
1// Using Callback Function 2 3imagekit.updateCustomMetadataField( 4 "field_id", 5 { 6 schema: { 7 minValue: 500, 8 maxValue: 2500 9 } 10 }, 11 function(error, result) { 12 if(error) console.log(error); 13 else console.log(result); 14 } 15); 16 17 18// Using Promises 19 20imagekit.updateCustomMetadataField( 21 "field_id", 22 { 23 schema: { 24 minValue: 500, 25 maxValue: 2500 26 } 27 }, 28).then(response => { 29 console.log(response); 30}).catch(error => { 31 console.log(error); 32});
Delete a custom metadata field
delete a custom metadata field as per the API documentation here
1// Using Callback Function
2
3imagekit.deleteCustomMetadataField(
4 "field_id",
5 function(error, result) {
6 if(error) console.log(error);
7 else console.log(result);
8 }
9);
10
11
12// Using Promises
13
14imagekit.deleteCustomMetadataField(
15 "field_id"
16).then(response => {
17 console.log(response);
18}).catch(error => {
19 console.log(error);
20});
We have included the following commonly used utility functions in this package.
If you want to implement client-side file upload, you will need a token, expiry timestamp, and a valid signature for that upload. The SDK provides a simple method you can use in your backend code to generate these authentication parameters.
Note: The Private API Key should never be exposed in any client-side code. You must always generate these authentication parameters on the server-side
1var authenticationParameters = imagekit.getAuthenticationParameters(token, expire);
Returns
1{ 2 token : "unique_token", 3 expire : "valid_expiry_timestamp", 4 signature : "generated_signature" 5}
Both the token
and expire
parameters are optional. If not specified, the SDK uses the uuid package to generate a random token and generate a valid expiry timestamp internally. token
and expire
are always returned in the response, no matter if they are provided as an input to this method or not.
Perceptual hashing allows you to construct a hash value that uniquely identifies an input image based on an image's contents. For example, ImageKit.io metadata API returns the pHash value of an image in the response. You can use this value to find a duplicate (or similar) image by calculating the distance between the two images' pHash value.
This SDK exposes the pHashDistance
function to calculate the distance between two pHash values. It accepts two pHash hexadecimal strings and returns a numeric value indicative of the level of difference between the two images.
1const calculateDistance = () => { 2 // asynchronously fetch metadata of two uploaded image files 3 // ... 4 // Extract pHash strings from both: say 'firstHash' and 'secondHash' 5 // ... 6 // Calculate the distance between them: 7 const distance = imagekit.pHashDistance(firstHash, secondHash); 8 return distance; 9}
1imagekit.pHashDistance('f06830ca9f1e3e90', 'f06830ca9f1e3e90'); 2// output: 0 (same image) 3 4imagekit.pHashDistance('2d5ad3936d2e015b', '2d6ed293db36a4fb'); 5// output: 17 (similar images) 6 7imagekit.pHashDistance('a4a65595ac94518b', '7838873e791f8400'); 8// output: 37 (dissimilar images)
You can access $ResponseMetadata
on success or error object to access the HTTP status code and response headers.
1// Success 2var response = await imagekit.getPurgeCacheStatus(requestId); 3console.log(response.$ResponseMetadata.statusCode); // 200 4 5// {'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'} 6console.log(response.$ResponseMetadata.headers); 7 8// Error 9try { 10 await imagekit.getPurgeCacheStatus(requestId); 11} catch (ex) { 12 console.log(response.$ResponseMetadata.statusCode); // 404 13 14 // {'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'} 15 console.log(response.$ResponseMetadata.headers); 16}
Except for upload API, all ImageKit APIs are rate limited to protect the infrastructure from excessive requests rates and to keep ImageKit.io fast and stable for everyone.
When you exceed the rate limits for an endpoint, you will receive a 429
status code. The Node.js library reads the rate limiting response headers provided in the API response and adds these in the error argument of the callback or .catch
when using promises. Please sleep/pause for the number of milliseconds specified by the value of the X-RateLimit-Reset
property before making additional requests to that endpoint.
Property | Description |
---|---|
X-RateLimit-Limit | The maximum number of requests that can be made to this endpoint in the interval specified by the X-RateLimit-Interval response header. |
X-RateLimit-Reset | The amount of time in milliseconds before you can make another request to this endpoint. Pause/sleep your workflow for this duration. |
X-RateLimit-Interval | The duration of interval in milliseconds for which this rate limit was exceeded. |
ImageKit sends x-ik-signature
in the webhook request header, which can be used to verify the authenticity of the webhook request.
Verifying webhook signature is easy with imagekit SDK. All you need is the value of the x-ik-signature
header, request body, and webhook secret from the ImageKit dashboard.
Here is an example using the express.js server.
1const express = require('express'); 2const Imagekit = require('imagekit'); 3 4// Webhook configs 5const WEBHOOK_SECRET = 'whsec_...'; // Copy from Imagekit dashboard 6const WEBHOOK_EXPIRY_DURATION = 300 * 1000; // 300 seconds for example 7 8const imagekit = new Imagekit({ 9 publicKey: 'public_...', 10 urlEndpoint: 'https://ik.imagekit.io/imagekit_id', 11 privateKey: 'private_...', 12}) 13 14const app = express(); 15 16app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { 17 const signature = req.headers["x-ik-signature"]; 18 const requestBody = req.body; 19 let webhookResult; 20 try { 21 webhookResult = imagekit.verifyWebhookEvent(requestBody, signature, WEBHOOK_SECRET); 22 } catch (e) { 23 // `verifyWebhookEvent` method will throw an error if signature is invalid 24 console.log(e); 25 res.status(400).send(`Webhook Error`); 26 } 27 28 const { timestamp, event } = webhookResult; 29 30 // Check if webhook has expired 31 if (timestamp + WEBHOOK_EXPIRY_DURATION < Date.now()) { 32 res.status(400).send(`Webhook Error`); 33 } 34 35 // Handle webhook 36 switch (event.type) { 37 case 'video.transformation.accepted': 38 // It is triggered when a new video transformation request is accepted for processing. You can use this for debugging purposes. 39 break; 40 case 'video.transformation.ready': 41 // It is triggered when a video encoding is finished, and the transformed resource is ready to be served. You should listen to this webhook and update any flag in your database or CMS against that particular asset so your application can start showing it to users. 42 break; 43 case 'video.transformation.error': 44 // It is triggered if an error occurs during encoding. Listen to this webhook to log the reason. You should check your origin and URL-endpoint settings if the reason is related to download failure. If the reason seems like an error on the ImageKit side, then raise a support ticket at support@imagekit.io. 45 break; 46 default: 47 // ... handle other event types 48 console.log(`Unhandled event type ${event.type}`); 49 } 50 51 // Return a response to acknowledge receipt of the event 52 res.send(); 53}) 54 55app.listen(3000, () => { 56 console.log(`Example app listening on port 3000`) 57})
For any feedback or to report any issues or general implementation support, please reach out to support@imagekit.io
Released under the MIT license.
No vulnerabilities found.
No security vulnerabilities found.