Launch Week Day 5: Introducing Reachability for PHP.Learn More
Socket
Book a DemoSign in
Socket

transloadit

Package Overview
Dependencies
Maintainers
3
Versions
90
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

transloadit

Node.js SDK for Transloadit

latest
Source
npmnpm
Version
4.10.0
Version published
Weekly downloads
23K
11.21%
Maintainers
3
Weekly downloads
 
Created
Source

Build Status Coverage

Transloadit Logo

This is the official Node.js SDK for Transloadit's file uploading and encoding service.

Intro

Transloadit is a service that helps you handle file uploads, resize, crop and watermark your images, make GIFs, transcode your videos, extract thumbnails, generate audio waveforms, and so much more. In short, Transloadit is the Swiss Army Knife for your files.

This is a Node.js SDK to make it easy to talk to the Transloadit REST API.

Requirements

  • Node.js version 20 or newer
  • A Transloadit account (free signup)
  • Your API credentials (authKey, authSecret)

Install

Inside your project, type:

yarn add @transloadit/node

or

npm install --save @transloadit/node

The legacy npm package name transloadit is kept as an alias for backward compatibility, but @transloadit/node is the canonical package name.

Command Line Interface (CLI)

This package includes a full-featured CLI for interacting with Transloadit from your terminal.

Quick Start

Pick one auth setup and then run the CLI.

Use shell env vars:

export TRANSLOADIT_KEY="YOUR_TRANSLOADIT_KEY"
export TRANSLOADIT_SECRET="YOUR_TRANSLOADIT_SECRET"

Or create a reusable home credentials file:

mkdir -p ~/.transloadit
cat > ~/.transloadit/credentials <<'EOF'
TRANSLOADIT_KEY="YOUR_TRANSLOADIT_KEY"
TRANSLOADIT_SECRET="YOUR_TRANSLOADIT_SECRET"
EOF
chmod 600 ~/.transloadit/credentials

Then see all available commands:

npx -y @transloadit/node --help

The CLI binary is still called transloadit, so command examples below may use npx transloadit ....

Credential Resolution

The CLI resolves authentication in this order:

  • Shell environment variables such as TRANSLOADIT_KEY, TRANSLOADIT_SECRET, and TRANSLOADIT_AUTH_TOKEN
  • The current working directory .env
  • ~/.transloadit/credentials

The home credentials file uses dotenv syntax. It is meant for user-level CLI use, so Intents and other commands work from any directory on your machine without having to export credentials first.

Example ~/.transloadit/credentials:

TRANSLOADIT_KEY="YOUR_TRANSLOADIT_KEY"
TRANSLOADIT_SECRET="YOUR_TRANSLOADIT_SECRET"
# Optional:
# TRANSLOADIT_ENDPOINT="https://api2.transloadit.com"
# TRANSLOADIT_AUTH_TOKEN="YOUR_BEARER_TOKEN"

If you want to use a different path, set TRANSLOADIT_CREDENTIALS_FILE=/abs/path/to/credentials.env.

Most commands can authenticate with either TRANSLOADIT_AUTH_TOKEN or TRANSLOADIT_KEY + TRANSLOADIT_SECRET. Commands that mint bearer tokens or generate signatures still require TRANSLOADIT_KEY and TRANSLOADIT_SECRET.

Minting Bearer Tokens (Hosted MCP)

If you want to connect an agent to the Transloadit-hosted MCP endpoint, mint a short-lived bearer token via POST /token. This command also uses the same credential resolution order above:

# Prints JSON to stdout (stderr may include npx/npm noise)
npx -y transloadit auth token --aud mcp

To reduce blast radius, you can request a narrower set of scopes. The server will only grant scopes that your Auth Key already has (it applies an intersection), and will error if you request scopes you are not allowed to use.

# Request a narrower token (comma-separated scopes)
npx -y transloadit auth token --aud mcp --scope assemblies:write,templates:read

Processing Media

For common one-off tasks, prefer the intent-first commands:

The full generated intent reference also lives in docs/intent-commands.md.

At a glance

Intent commands are the fastest path to common one-off tasks from the CLI. Authentication is resolved in this order: shell environment, the current working directory .env, then ~/.transloadit/credentials. The home credentials file uses dotenv syntax and can include TRANSLOADIT_KEY, TRANSLOADIT_SECRET, TRANSLOADIT_ENDPOINT, and TRANSLOADIT_AUTH_TOKEN. Use --print-urls when you want temporary result URLs without downloading locally. All intent commands also support the global CLI flags --json, --log-level, --endpoint, and --help.

CommandWhat it doesInputOutput
image generateGenerate images from text promptsfile, dir, URL, base64file
preview generateGenerate a preview thumbnailfile, dir, URL, base64file
image remove-backgroundRemove the background from imagesfile, dir, URL, base64file
image mergeMerge several images into a single imagefile, dir, URL, base64file
image optimizeOptimize images without quality lossfile, dir, URL, base64file
image resizeConvert, resize, or watermark imagesfile, dir, URL, base64file
image upscaleUpscale imagesfile, dir, URL, base64file
document convertConvert documents into different formatsfile, dir, URL, base64file
document optimizeReduce PDF file sizefile, dir, URL, base64file
document auto-rotateAuto-rotate documents to the correct orientationfile, dir, URL, base64file
document thumbsExtract thumbnail images from documentsfile, dir, URL, base64directory
audio waveformGenerate waveform images from audiofile, dir, URL, base64file
text speakSpeak textfile, dir, URL, base64file
video thumbsExtract thumbnails from videosfile, dir, URL, base64directory
video encode-hlsRun builtin/encode-hls-video@latestfile, dir, URL, base64directory
image describeDescribe images as labels or publishable text fieldsfile, dir, URL, base64file
markdown pdfRender Markdown files as PDFsfile, dir, URL, base64file
markdown docxRender Markdown files as DOCX documentsfile, dir, URL, base64file
file compressCompress filesfile, dir, URL, base64file
file decompressDecompress archivesfile, dir, URL, base64directory

If you omit --output, the CLI writes next to a single local file input when it can, otherwise it falls back to the current working directory. Use --print-urls alone when you want URLs without downloading locally.

Shared flags

These flags are available across many intent commands, so the per-command sections below focus on differences.

Shared file input & output flags

FlagTypeRequiredExampleDescription
--input, -ipath | dir | url | -variesinput.fileProvide an input path, directory, URL, or - for stdin
--input-base64base64 | data URLnodata:text/plain;base64,SGVsbG8=Provide base64-encoded input content directly
--output, -opathnooutput.fileWrite the result to this path or directory. If omitted, the CLI infers a local output path.
--print-urlsbooleannofalsePrint temporary result URLs after completion

Shared no-input output flags

FlagTypeRequiredExampleDescription
--output, -opathnooutput.fileWrite the result to this path. If omitted, the CLI infers a local output path.
--print-urlsbooleannofalsePrint temporary result URLs after completion

Shared processing flags

FlagTypeRequiredExampleDescription
--recursive, -rbooleannofalseEnumerate input directories recursively
--delete-after-processing, -dbooleannofalseDelete input files after they are processed
--reprocess-stalebooleannofalseProcess inputs even if output is newer

Shared watch flags

FlagTypeRequiredExampleDescription
--watch, -wbooleannofalseWatch inputs for changes
--concurrency, -cnumberno5Maximum number of concurrent assemblies (default: 5)

Shared bundling flags

FlagTypeRequiredExampleDescription
--single-assemblybooleannofalsePass all input files to a single assembly instead of one assembly per file

image generate

Generate images from text prompts

Runs /image/generate. Without inputs, this is text-to-image. With one or more --input files, the inputs are bundled into a single assembly so the prompt can refer to them by filename.

Usage

npx transloadit image generate [--input <path|dir|url|->] [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: single assembly
  • Backend: semantic alias image-generate

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags listed above.

Command options

FlagTypeRequiredExampleDescription
--promptstringyes"A red bicycle in a studio"The prompt describing the desired image content.
--modelstringnogoogle/nano-banana-2The AI model to use for image generation. Defaults to google/nano-banana-2. Backend-supported models include openai/gpt-image-2 and Google Nano Banana variants.
--formatstringnojpgFormat of the generated image.
--seednumbernoSeed for the random number generator.
--aspect-ratiostringnoAspect ratio of the generated image.
--heightnumbernoHeight of the generated image.
--widthnumbernoWidth of the generated image.
--stylestringnoStyle of the generated image.
--num-outputsnumbernoNumber of image variants to generate.

Examples

# Generate an image from text
transloadit image generate --prompt "A red bicycle in a studio" --output output.png
# Generate with OpenAI gpt-image-2
transloadit image generate --model openai/gpt-image-2 --width 1024 --height 1024 --prompt "A ceramic coffee mug on a white sweep" --output output.png
# Guide generation with one input image
transloadit image generate --input subject.jpg --prompt "Place subject.jpg on a magazine cover" --output output.png
# Guide generation with multiple input images
transloadit image generate --input person1.jpg --input person2.jpg --input background.jpg --prompt "Place person1.jpg feeding person2.jpg in front of background.jpg" --output output.png

preview generate

Generate a preview thumbnail

Runs /file/preview on each input file and writes the result to --output.

Usage

npx transloadit preview generate --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /file/preview

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--formatstringnojpgThe output format for the generated thumbnail image. If a short video clip is generated using the clip strategy, its format is defined by clip_format.
--widthnumberno1Width of the thumbnail, in pixels.
--heightnumberno1Height of the thumbnail, in pixels.
--resize-strategystringnocropTo achieve the desired dimensions of the preview thumbnail, the Robot might have to resize the generated image.
--backgroundstringnovalueThe hexadecimal code of the color used to fill the background (only used for the pad resize strategy).
--zoombooleannotrueIf set to false, smaller images will not be stretched to the desired width and height.
--strategyjsonnovalueDefinition of the thumbnail generation process per file category.
--artwork-outer-colorstringnovalueThe color used in the outer parts of the artwork's gradient.
--artwork-center-colorstringnovalueThe color used in the center of the artwork's gradient.
--waveform-center-colorstringnovalueThe color used in the center of the waveform's gradient. The format is #rrggbb[aa] (red, green, blue, alpha). Only used if the waveform strategy for audio files is applied.
--waveform-outer-colorstringnovalueThe color used in the outer parts of the waveform's gradient. The format is #rrggbb[aa] (red, green, blue, alpha). Only used if the waveform strategy for audio files is applied.
--waveform-heightnumberno1Height of the waveform, in pixels. Only used if the waveform strategy for audio files is applied. It can be utilized to ensure that the waveform only takes up a section of the…
--waveform-widthnumberno1Width of the waveform, in pixels. Only used if the waveform strategy for audio files is applied. It can be utilized to ensure that the waveform only takes up a section of the…
--icon-stylestringnosquareThe style of the icon generated if the icon strategy is applied.
--icon-text-colorstringnovalueThe color of the text used in the icon. The format is #rrggbb[aa]. Only used if the icon strategy is applied.
--icon-text-fontstringnovalueThe font family of the text used in the icon. Only used if the icon strategy is applied. Here is a list of all supported fonts.
--icon-text-contentstringnoextensionThe content of the text box in generated icons. Only used if the icon_style parameter is set to with-text. The default value, extension, adds the file extension (e.g. MP4, JPEG)…
--optimizebooleannotrueSpecifies whether the generated preview image should be optimized to reduce the image's file size while keeping their quaility.
--optimize-prioritystringnocompression-ratioSpecifies whether conversion speed or compression ratio is prioritized when optimizing images.
--optimize-progressivebooleannotrueSpecifies whether images should be interlaced, which makes the result image load progressively in browsers.
--clip-formatstringnoapngThe animated image format for the generated video clip. Only used if the clip strategy for video files is applied. Please consult the MDN Web Docs for detailed information about…
--clip-offsetnumberno1The start position in seconds of where the clip is cut. Only used if the clip strategy for video files is applied. Be aware that for larger video only the first few MBs of the…
--clip-durationnumberno1The duration in seconds of the generated video clip. Only used if the clip strategy for video files is applied. Be aware that a longer clip duration also results in a larger file…
--clip-frameratenumberno1The framerate of the generated video clip. Only used if the clip strategy for video files is applied. Be aware that a higher framerate appears smoother but also results in a…
--clip-loopbooleannotrueSpecifies whether the generated animated image should loop forever (true) or stop after playing the animation once (false).

Examples

transloadit preview generate --input input.file --output output.file

image remove-background

Remove the background from images

Runs /image/bgremove on each input file and writes the result to --output.

Usage

npx transloadit image remove-background --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /image/bgremove

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--selectstringnoforegroundRegion to select and keep in the image. The other region is removed.
--formatstringnopngFormat of the generated image. Defaults to PNG when not provided.
--providerstringnoawsProvider to use for removing the background.
--modelstringnovalueProvider-specific model to use for removing the background. Mostly intended for testing and evaluation.

Examples

transloadit image remove-background --input input.png --output output.png

image merge

Merge several images into a single image

Runs /image/merge for the provided inputs and writes the result to --output.

Usage

npx transloadit image merge --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: single assembly
  • Backend: /image/merge

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags listed above.

Command options

FlagTypeRequiredExampleDescription
--formatstringnojpgThe output format for the modified image.
--directionstringnohorizontalSpecifies the direction which the images are displayed. Only applies to the default spritesheet layout. Ignored when effect is set to polaroid-stack or mosaic, as those effects…
--effectstringnomosaicApplies a styled collage layout instead of a plain horizontal or vertical spritesheet.
--bordernumberno1An integer value which defines the gap between images on the spritesheet.
--backgroundstringnotransparentEither the hexadecimal code or name of the color used to fill the background (only shown with a border > 1).
--widthnumberno1The output canvas width in pixels. This is mainly used by styled effects such as polaroid-stack and mosaic.
--heightnumberno1The output canvas height in pixels. This is mainly used by styled effects such as polaroid-stack and mosaic.
--seednumberno1Optional deterministic seed used by styled effects such as polaroid-stack and mosaic.
--shufflebooleannotrueWhether styled effects such as polaroid-stack and mosaic may shuffle the input order before laying out the canvas.
--coveragenumberno1Area-coverage multiplier for the polaroid-stack effect. Controls how large each polaroid is relative to the canvas and consequently how much of the canvas is covered by photos.…
--adaptive-filteringbooleannotrueControls the image compression for PNG images. Setting to true results in smaller file size, while increasing processing time. It is encouraged to keep this option disabled.
--qualitynumberno1Controls the image compression for JPG, PNG, and WebP images. Please also take a look at 🤖/image/optimize.

Examples

transloadit image merge --input input.png --output output.png

image optimize

Optimize images without quality loss

Runs /image/optimize on each input file and writes the result to --output.

Usage

npx transloadit image optimize --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /image/optimize

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--prioritystringnocompression-ratioProvides different algorithms for better or worse compression for your images, but that run slower or faster.
--progressivebooleannotrueInterlaces the image if set to true, which makes the result image load progressively in browsers.
--preserve-meta-databooleannotrueSpecifies if the image's metadata should be preserved during the optimization, or not.
--fix-breaking-imagesbooleannotrueIf set to true this parameter tries to fix images that would otherwise make the underlying tool error out and thereby break your Assemblies .
--lossybooleannotrueWhen set to false (the default), only lossless PNG optimizers are used, disabling pngquant to preserve color accuracy.

Examples

transloadit image optimize --input input.png --output output.png

image resize

Convert, resize, or watermark images

Runs /image/resize on each input file and writes the result to --output.

Usage

npx transloadit image resize --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /image/resize

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--formatstringnovalueThe output format for the modified image. Some of the most important available formats are "jpg", "png", "gif", and "tiff". For a complete lists of all formats that we can write…
--widthnumberno1Width of the result in pixels. If not specified, will default to the width of the original.
--heightnumberno1Height of the new image, in pixels. If not specified, will default to the height of the input image.
--resize-strategystringnocropSee the list of available resize strategies.
--zoombooleannotrueIf this is set to false, smaller images will not be stretched to the desired width and height.
--cropautonovalueSpecify an object containing coordinates for the top left and bottom right corners of the rectangle to be cropped from the original image(s).
--gravitystringnobottomThe direction from which the image is to be cropped, when "resize_strategy" is set to "crop", but no crop coordinates are defined.
--stripbooleannotrueStrips all metadata from the image. This is useful to keep thumbnails as small as possible.
--alphastringnoActivateGives control of the alpha/matte channel of an image.
--preclip-alphastringnoActivateGives control of the alpha/matte channel of an image before applying the clipping path via clip: true.
--flattenbooleannotrueFlattens all layers onto the specified background to achieve better results from transparent formats to non-transparent formats, as explained in the ImageMagick documentation.
--correct-gammabooleannotruePrevents gamma errors common in many image scaling algorithms.
--qualitynumberno1Controls the image compression for JPG and PNG images. Please also take a look at 🤖/image/optimize.
--adaptive-filteringbooleannotrueControls the image compression for PNG images. Setting to true results in smaller file size, while increasing processing time. It is encouraged to keep this option disabled.
--backgroundstringnotransparentEither the hexadecimal code or name of the color used to fill the background (used for the pad resize strategy).
--framenumberno1Use this parameter when dealing with animated GIF files to specify which frame of the GIF is used for the operation.
--colorspacestringnoCMYSets the image colorspace. For details about the available values, see the ImageMagick documentation. Please note that if you were using "RGB", we recommend using "sRGB" instead…
--typestringnoBilevelSets the image color type. For details about the available values, see the ImageMagick documentation. If you're using colorspace, ImageMagick might try to find the most efficient…
--sepianumberno1Applies a sepia tone effect in percent.
--rotationautonoautoDetermines whether the image should be rotated. Use any number to specify the rotation angle in degrees (e.g., 90, 180, 270, 360, or precise values like 2.9). Use the value true…
--compressstringnoBZipSpecifies pixel compression for when the image is written. Compression is disabled by default. Please also take a look at 🤖/image/optimize.
--blurstringnovalueSpecifies gaussian blur, using a value with the form {radius}x{sigma}.
--blur-regionsjsonnovalueSpecifies an array of ellipse objects that should be blurred on the image.
--brightnessnumberno1Increases or decreases the brightness of the image by using a multiplier. For example 1.5 would increase the brightness by 50%, and 0.75 would decrease the brightness by 25%.
--saturationnumberno1Increases or decreases the saturation of the image by using a multiplier. For example 1.5 would increase the saturation by 50%, and 0.75 would decrease the saturation by 25%.
--huenumberno1Changes the hue by rotating the color of the image. The value 100 would produce no change whereas 0 and 200 will negate the colors in the image.
--contrastnumberno1Adjusts the contrast of the image. A value of 1 produces no change. Values below 1 decrease contrast (with 0 being minimum contrast), and values above 1 increase contrast (with 2…
--watermark-urlstringnovalueA URL indicating a PNG image to be overlaid above this image.
--watermark-positionstring[]nobottomThe position at which the watermark is placed. The available options are "center", "top", "bottom", "left", and "right". You can also combine options, such as "bottom-right". An…
--watermark-x-offsetnumberno1The x-offset in number of pixels at which the watermark will be placed in relation to the position it has due to watermark_position.
--watermark-y-offsetnumberno1The y-offset in number of pixels at which the watermark will be placed in relation to the position it has due to watermark_position.
--watermark-sizestringnovalueThe size of the watermark, as a percentage. For example, a value of "50%" means that size of the watermark will be 50% of the size of image on which it is placed. The exact…
--watermark-resize-strategystringnoareaAvailable values are "fit", "min_fit", "stretch" and "area".
--watermark-opacitynumberno1The opacity of the watermark, where 0.0 is fully transparent and 1.0 is fully opaque.
--watermark-repeat-xbooleannotrueWhen set to true, the watermark will be repeated horizontally across the entire width of the image.
--watermark-repeat-ybooleannotrueWhen set to true, the watermark will be repeated vertically across the entire height of the image.
--textjsonnovalueText overlays to be applied to the image. Can be either a single text object or an array of text objects. Each text object contains text rules. The following text parameters are…
--progressivebooleannotrueInterlaces the image if set to true, which makes the image load progressively in browsers.
--transparentstringnotransparentMake this color transparent within the image. Example: "255,255,255".
--trim-whitespacebooleannotrueThis determines if additional whitespace around the image should first be trimmed away.
--clipautonovalueApply the clipping path to other operations in the resize job, if one is present.
--negatebooleannotrueReplace each pixel with its complementary color, effectively negating the image. Especially useful when testing clipping.
--clutbooleannotrueApplies a Color Look-Up Table (CLUT) image to remap the colors of the input image using ImageMagick's -clut operator.
--densitystringnovalueWhile in-memory quality and file format depth specifies the color resolution, the density of an image is the spatial (space) resolution of the image.
--monochromebooleannotrueTransform the image to black and white. This is a shortcut for setting the colorspace to Gray and type to Bilevel.
--shaveautonovalueShave pixels from the image edges. The value should be in the format width or widthxheight to specify the number of pixels to remove from each side.

Examples

transloadit image resize --input input.png --output output.png

image upscale

Upscale images

Runs /image/upscale on each input file and writes the result to --output.

Usage

npx transloadit image upscale --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /image/upscale

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--modelstringnonightmareai/real-esrganThe AI model to use for image upscaling. Defaults to nightmareai/real-esrgan.
--scalenumberno2Upscale factor. Defaults to 2.
--face-enhancebooleannotrueEnable face enhancement for better face restoration. Defaults to false.

Examples

transloadit image upscale --input input.png --output output.png

document convert

Convert documents into different formats

Runs /document/convert on each input file and writes the result to --output.

Usage

npx transloadit document convert --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /document/convert

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--formatstringyespdfThe desired format for document conversion.
--markdown-formatstringnocommonmarkMarkdown can be represented in several variants, so when using this Robot to transform Markdown into HTML please specify which revision is being used.
--markdown-themestringnobareThis parameter overhauls your Markdown files styling based on several canned presets.
--pdf-marginstringnovaluePDF Paper margins, separated by , and with units. We support the following unit values: px, in, cm, mm. Currently this parameter is only supported when converting from html.
--pdf-print-backgroundbooleannotruePrint PDF background graphics. Currently this parameter is only supported when converting from html.
--pdf-formatstringnoA0PDF paper format. Currently this parameter is only supported when converting from html.
--pdf-display-header-footerbooleannotrueDisplay PDF header and footer. Currently this parameter is only supported when converting from html.
--pdf-header-templatestringnovalueHTML template for the PDF print header. Should be valid HTML markup with following classes used to inject printing values into them: - date formatted print date - title document…
--pdf-footer-templatestringnovalueHTML template for the PDF print footer. Should use the same format as the pdf_header_template. Currently this parameter is only supported when converting from html, and requires…

Examples

transloadit document convert --input input.pdf --format pdf --output output.pdf

document optimize

Reduce PDF file size

Runs /document/optimize on each input file and writes the result to --output.

Usage

npx transloadit document optimize --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /document/optimize

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--presetstringnoscreenThe quality preset to use for optimization. Each preset provides a different balance between file size and quality: - screen - Lowest quality, smallest file size. Best for screen…
--image-dpinumberno1Target DPI (dots per inch) for embedded images. When specified, this overrides the DPI setting from the preset. Higher DPI values result in better image quality but larger file…
--compress-fontsbooleannotrueWhether to compress embedded fonts. When enabled, fonts are compressed to reduce file size.
--subset-fontsbooleannotrueWhether to subset embedded fonts, keeping only the glyphs that are actually used in the document.
--remove-metadatabooleannotrueWhether to strip document metadata (title, author, keywords, etc.) from the PDF. This can provide a small reduction in file size and may be useful for privacy.
--linearizebooleannotrueWhether to linearize (optimize for Fast Web View) the output PDF.
--compatibilitystringno1.4The PDF version compatibility level. Lower versions have broader compatibility but fewer features. Higher versions support more advanced features but may not open in older PDF…

Examples

transloadit document optimize --input input.pdf --output output.pdf

document auto-rotate

Auto-rotate documents to the correct orientation

Runs /document/autorotate on each input file and writes the result to --output.

Usage

npx transloadit document auto-rotate --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /document/autorotate

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Examples

transloadit document auto-rotate --input input.pdf --output output.pdf

document thumbs

Extract thumbnail images from documents

Runs /document/thumbs on each input file and writes the results to --output.

Usage

npx transloadit document thumbs --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: directory
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /document/thumbs

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--pagenumberno1The PDF page that you want to convert to an image. By default the value is null which means that all pages will be converted into images.
--page-rangestringnovalueA page range to extract, in the format "start-end" (e.g., "1-20").
--formatstringnojpgThe format of the extracted image(s). If you specify the value "gif", then an animated gif cycling through all pages is created. Please check out this demo to learn more about…
--delaynumberno1If your output format is "gif" then this parameter sets the number of 100th seconds to pass before the next frame is shown in the animation.
--widthnumberno1Width of the new image, in pixels. If not specified, will default to the width of the input image
--heightnumberno1Height of the new image, in pixels. If not specified, will default to the height of the input image
--resize-strategystringnocropOne of the available resize strategies.
--backgroundstringnovalueEither the hexadecimal code or name of the color used to fill the background (only used for the pad resize strategy).
--alphastringnoRemoveChange how the alpha channel of the resulting image should work.
--densitystringnovalueWhile in-memory quality and file format depth specifies the color resolution, the density of an image is the spatial (space) resolution of the image.
--antialiasingbooleannotrueControls whether or not antialiasing is used to remove jagged edges from text or images in a document.
--colorspacestringnoCMYSets the image colorspace. For details about the available values, see the ImageMagick documentation. Please note that if you were using "RGB", we recommend using "sRGB".…
--trim-whitespacebooleannotrueThis determines if additional whitespace around the PDF should first be trimmed away before it is converted to an image.
--pdf-use-cropboxbooleannotrueSome PDF documents lie about their dimensions. For instance they'll say they are landscape, but when opened in decent Desktop readers, it's really in portrait mode. This can…
--turbobooleannotrueEnables high-performance mode for faster document processing.

Examples

transloadit document thumbs --input input.pdf --output output/

audio waveform

Generate waveform images from audio

Runs /audio/waveform on each input file and writes the result to --output.

Usage

npx transloadit audio waveform --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /audio/waveform

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--ffmpegjsonnovalueA parameter object to be passed to FFmpeg. If a preset is used, the options specified are merged on top of the ones from the preset. For available options, see the FFmpeg…
--formatstringnoimageThe format of the result file. Can be "image" or "json". If "image" is supplied, a PNG image will be created, otherwise a JSON file. When style is "spectrogram", only "image" is…
--widthnumberno1The width of the resulting image if the format "image" was selected.
--heightnumberno1The height of the resulting image if the format "image" was selected.
--antialiasingautono0Either a value of 0 or 1, or true/false, corresponding to if you want to enable antialiasing to achieve smoother edges in the waveform graph or not.
--background-colorstringnovalueThe background color of the resulting image in the "rrggbbaa" format (red, green, blue, alpha), if the format "image" was selected.
--center-colorstringnovalueThe color used in the center of the gradient. The format is "rrggbbaa" (red, green, blue, alpha).
--outer-colorstringnovalueThe color used in the outer parts of the gradient. The format is "rrggbbaa" (red, green, blue, alpha).
--stylestringnov0Waveform style version. - "v0": Legacy waveform generation (default). - "v1": Advanced waveform generation with additional parameters. - "spectrogram": Spectrogram visualization…
--split-channelsbooleannotrueAvailable when style is "v1". If set to true, outputs multi-channel waveform data or image files, one per channel.
--zoomnumberno1Available when style is "v1". Zoom level in samples per pixel. This parameter cannot be used together with pixels_per_second.
--pixels-per-secondnumberno1Available when style is "v1". Zoom level in pixels per second. This parameter cannot be used together with zoom.
--bitsnumberno8Available when style is "v1". Bit depth for waveform data. Can be 8 or 16.
--startnumberno1Available when style is "v1". Start time in seconds.
--endnumberno1Available when style is "v1". End time in seconds (0 means end of audio).
--colorsstringnoauditionAvailable when style is "v1". Color scheme to use. Can be "audition" or "audacity".
--border-colorstringnovalueAvailable when style is "v1". Border color in "rrggbbaa" format.
--waveform-stylestringnonormalAvailable when style is "v1". Waveform style. Can be "normal" or "bars".
--bar-widthnumberno1Available when style is "v1". Width of bars in pixels when waveform_style is "bars".
--bar-gapnumberno1Available when style is "v1". Gap between bars in pixels when waveform_style is "bars".
--bar-stylestringnosquareAvailable when style is "v1". Bar style when waveform_style is "bars".
--axis-label-colorstringnovalueAvailable when style is "v1". Color for axis labels in "rrggbbaa" format.
--no-axis-labelsbooleannotrueAvailable when style is "v1". If set to true, renders waveform image without axis labels.
--with-axis-labelsbooleannotrueAvailable when style is "v1". If set to true, renders waveform image with axis labels.
--amplitude-scalenumberno1Available when style is "v1". Amplitude scale factor.
--compressionnumberno1Available when style is "v1". PNG compression level: 0 (none) to 9 (best), or -1 (default). Only applicable when format is "image".
--color-mapstringnoviridisAvailable when style is "spectrogram". Color scheme for the spectrogram visualization. Defaults to "viridis".
--frequency-scalestringnolinearAvailable when style is "spectrogram". Frequency scale for the spectrogram. "linear" shows frequencies evenly spaced, "logarithmic" emphasizes lower frequencies. Defaults to…
--frequency-minnumberno1Available when style is "spectrogram". Minimum frequency in Hz to display. Defaults to 0.
--frequency-maxnumberno1Available when style is "spectrogram". Maximum frequency in Hz to display. Defaults to half the sample rate (Nyquist frequency).
--legendbooleannotrueAvailable when style is "spectrogram". Whether to include a legend showing the frequency and time scales. Defaults to false.
--gainnumberno1Available when style is "spectrogram". Linear gain factor for spectrogram intensity. Defaults to 1.
--orientationstringnoverticalAvailable when style is "spectrogram". Orientation of the spectrogram. "horizontal" shows time on the x-axis (default), "vertical" shows time on the y-axis.

Examples

transloadit audio waveform --input input.mp3 --output output.png

text speak

Speak text

Runs /text/speak on each input file and writes the result to --output.

Usage

npx transloadit text speak [--input <path|dir|url|->] [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /text/speak

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--promptstringno"A red bicycle in a studio"Which text to speak. You can also set this to null and supply an input text file.
--providerstringyesawsWhich AI provider to leverage. Transloadit outsources this task and abstracts the interface so you can expect the same data structures, but different latencies and information…
--target-languagestringnoen-USThe written language of the document. This will also be the language of the spoken text. The language should be specified in the BCP-47 format, such as "en-GB", "de-DE" or…
--voicestringnofemale-1The gender to be used for voice synthesis. Please consult the list of supported languages and voices.
--ssmlbooleannotrueSupply Speech Synthesis Markup Language instead of raw text, in order to gain more control over how your text is voiced, including rests and pronounciations.

Examples

transloadit text speak --input input.pdf --provider aws --output output.mp3

video thumbs

Extract thumbnails from videos

Runs /video/thumbs on each input file and writes the results to --output.

Usage

npx transloadit video thumbs --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: directory
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /video/thumbs

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--ffmpegjsonnovalueA parameter object to be passed to FFmpeg. If a preset is used, the options specified are merged on top of the ones from the preset. For available options, see the FFmpeg…
--countnumberno1The number of thumbnails to be extracted. As some videos have incorrect durations, the actual number of thumbnails generated may be less in rare cases. The maximum number of…
--offsetsautonovalueAn array of offsets representing seconds of the file duration, such as [ 2, 45, 120 ].
--formatstringnojpgThe format of the extracted thumbnail. Supported values are "jpg", "jpeg" and "png". Even if you specify the format to be "jpeg" the resulting thumbnails will have a "jpg" file…
--widthnumberno1The width of the thumbnail, in pixels. Defaults to the original width of the video.
--heightnumberno1The height of the thumbnail, in pixels. Defaults to the original height of the video.
--resize-strategystringnocropOne of the available resize strategies.
--backgroundstringnovalueThe background color of the resulting thumbnails in the "rrggbbaa" format (red, green, blue, alpha) when used with the "pad" resize strategy. The default color is black.
--rotatenumberno0Forces the video to be rotated by the specified degree integer.
--input-codecstringnovalueSpecifies the input codec to use when decoding the video. This is useful for videos with special codecs that require specific decoders.

Examples

transloadit video thumbs --input input.mp4 --output output/

video encode-hls

Run builtin/encode-hls-video@latest

Runs the builtin/encode-hls-video@latest template and writes the outputs to --output.

Usage

npx transloadit video encode-hls --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: directory
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: builtin/encode-hls-video@latest

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Examples

transloadit video encode-hls --input input.mp4 --output output/

image describe

Describe images as labels or publishable text fields

Generates image labels through /image/describe, or structured altText/title/caption/description through /ai/chat, then writes the JSON result to --output.

Usage

npx transloadit image describe --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --watch
  • Backend: semantic alias image-describe

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags listed above.

Command options

FlagTypeRequiredExampleDescription
--fieldsstring[]noDescribe output fields to generate, for example labels or altText,title,caption,description
--forstringnoUse a named output profile, currently: wordpress
--modelstringnoModel to use for generated text fields (default: anthropic/claude-4-sonnet-20250514)

Examples

# Describe an image as labels
transloadit image describe --input hero.jpg --output labels.json
# Generate WordPress-ready fields
transloadit image describe --input hero.jpg --for wordpress --output fields.json
# Request a custom field set
transloadit image describe --input hero.jpg --fields altText,title,caption --output fields.json

markdown pdf

Render Markdown files as PDFs

Runs /document/convert with format: pdf, letting the backend render Markdown and preserve features such as internal heading links in the generated PDF.

Usage

npx transloadit markdown pdf --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --watch
  • Backend: semantic alias markdown-pdf

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags listed above.

Command options

FlagTypeRequiredExampleDescription
--markdown-formatstringnoMarkdown variant to parse, either commonmark or gfm
--markdown-themestringnoMarkdown theme to render, either github or bare

Examples

# Render a Markdown file as a PDF file
transloadit markdown pdf --input README.md --output README.pdf
# Print a temporary result URL without downloading locally
transloadit markdown pdf --input README.md --print-urls

markdown docx

Render Markdown files as DOCX documents

Runs /document/convert with format: docx, letting the backend render Markdown and convert it into a Word document.

Usage

npx transloadit markdown docx --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: per-file; supports --watch
  • Backend: semantic alias markdown-docx

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags listed above.

Command options

FlagTypeRequiredExampleDescription
--markdown-formatstringnoMarkdown variant to parse, either commonmark or gfm
--markdown-themestringnoMarkdown theme to render, either github or bare

Examples

# Render a Markdown file as a DOCX file
transloadit markdown docx --input README.md --output README.docx
# Print a temporary result URL without downloading locally
transloadit markdown docx --input README.md --print-urls

file compress

Compress files

Runs /file/compress for the provided inputs and writes the result to --output.

Usage

npx transloadit file compress --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: file
  • Execution: single assembly
  • Backend: /file/compress

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags listed above.

Command options

FlagTypeRequiredExampleDescription
--formatstringnozipThe format of the archive to be created. Supported values are "tar" and "zip". Note that "tar" without setting gzip to true results in an archive that's not compressed in any way.
--gzipbooleannotrueDetermines if the result archive should also be gzipped. Gzip compression is only applied if you use the "tar" format.
--passwordstringnovalueThis allows you to encrypt all archive contents with a password and thereby protect it against unauthorized use.
--compression-levelnumberno1Determines how fiercely to try to compress the archive. -0 is compressionless, which is suitable for media that is already compressed. -1 is fastest with lowest compression. -9…
--file-layoutstringnoadvancedDetermines if the result archive should contain all files in one directory (value for this is "simple") or in subfolders according to the explanation below (value for this is…
--archive-namestringnovalueThe name of the archive file to be created (without the file extension).
--pathstringnovalueThe path at which each file is to be placed inside the archive.

Examples

transloadit file compress --input input.file --output output.file

file decompress

Decompress archives

Runs /file/decompress on each input file and writes the results to --output.

Usage

npx transloadit file decompress --input <path|dir|url|-> [options]

Quick facts

  • Input: file, dir, URL, base64
  • Output: directory
  • Execution: per-file; supports --single-assembly and --watch
  • Backend: /file/decompress

Shared flags

  • Uses the shared file input and output flags listed above.
  • Also supports the shared base processing flags, watch flags, bundling flags listed above.

Command options

FlagTypeRequiredExampleDescription
--passwordstringnovalueThe password to use for decrypting password-protected archives.
--turbobooleannotrueEnables Turbo Mode for /file/decompress. This setting defaults to true. Set it to false to disable Turbo Mode. When enabled, extracted files are emitted as soon as they are…

Examples

transloadit file decompress --input input.file --output output/

For full control, create Assemblies directly using Assembly Instructions (steps) or Templates:

# Process a file using a steps file
npx transloadit assemblies create --steps steps.json --input image.jpg --output result.jpg

# Process using a Template
npx transloadit assemblies create --template YOUR_TEMPLATE_ID --input image.jpg --output result.jpg

# Process with custom fields
npx transloadit assemblies create --template YOUR_TEMPLATE_ID --field size=100 --input image.jpg --output thumb.jpg

# Process a directory of files
npx transloadit assemblies create --template YOUR_TEMPLATE_ID --input images/ --output thumbs/

# Process recursively with file watching
npx transloadit assemblies create --template YOUR_TEMPLATE_ID --input images/ --output thumbs/ --recursive --watch

# Process multiple files in a single assembly
npx transloadit assemblies create --template YOUR_TEMPLATE_ID --input file1.jpg --input file2.jpg --output results/ --single-assembly

# Limit concurrent processing (default: 5)
npx transloadit assemblies create --template YOUR_TEMPLATE_ID --input images/ --output thumbs/ --concurrency 2

Managing Assemblies

# List recent assemblies
npx transloadit assemblies list

# List assemblies with filters
npx transloadit assemblies list --after 2024-01-01 --before 2024-12-31

# Get assembly status
npx transloadit assemblies get ASSEMBLY_ID

# Cancel an assembly
npx transloadit assemblies delete ASSEMBLY_ID

# Replay an assembly (re-run with original instructions)
npx transloadit assemblies replay ASSEMBLY_ID

# Replay with different steps
npx transloadit assemblies replay --steps new-steps.json ASSEMBLY_ID

# Replay using latest template version
npx transloadit assemblies replay --reparse-template ASSEMBLY_ID

Linting Assembly Instructions

Lint Assembly Instructions locally using the same linter as the API.

# From a JSON file (full instructions or steps-only)
npx transloadit assemblies lint --steps steps.json

# From stdin
cat steps.json | npx transloadit assemblies lint

# Merge template content before linting
npx transloadit assemblies lint --template TEMPLATE_ID --steps steps.json

# Treat warnings as fatal; apply fixes (overwrites files / stdout for stdin)
npx transloadit assemblies lint --fatal warning --fix --steps steps.json

When both --template and steps input are provided, Transloadit merges the template content with the provided steps before linting, matching the API's runtime behavior. If the template sets allow_steps_override=false, providing steps will fail with TEMPLATE_DENIES_STEPS_OVERRIDE.

SDK Helpers

prepareInputFiles

prepareInputFiles() converts mixed file inputs into files, uploads, and optional /http/import steps so you can pass them directly into createAssembly() or resumeAssemblyUploads().

import { prepareInputFiles } from '@transloadit/node'

const prepared = await prepareInputFiles({
  inputFiles: [
    { kind: 'path', field: 'video', path: '/tmp/video.mp4' },
    { kind: 'base64', field: 'logo', filename: 'logo.png', base64: '...' },
    { kind: 'url', field: 'remote', url: 'https://example.com/file.jpg' },
  ],
  params: {
    steps: {
      ':original': { robot: '/upload/handle' },
      encode: { robot: '/video/encode', use: ':original' },
    },
  },
  base64Strategy: 'tempfile',
  urlStrategy: 'import-if-present',
  maxBase64Bytes: 512_000,
  allowPrivateUrls: true,
})

await client.createAssembly({
  params: prepared.params,
  files: prepared.files,
  uploads: prepared.uploads,
})

Options:

  • inputFiles – Array of { kind, field, ... } entries for path, base64, or url inputs.
  • params – Assembly instructions; steps will be extended when URL imports are injected.
  • fields – Extra form fields to merge into params.fields.
  • base64Strategy'buffer' (default) or 'tempfile' for base64 inputs.
  • urlStrategy'import', 'download', or 'import-if-present' (default 'import').
  • maxBase64Bytes – Optional size cap (decoded bytes). Overages throw before decoding.
  • allowPrivateUrls – Allow downloading private/loopback URLs when using urlStrategy: 'download' (default true). Hosted deployments should disable this.
  • tempDir – Optional temp directory base when base64Strategy: 'tempfile'.

Managing Templates

# List all templates
npx transloadit templates list

# Get template content
npx transloadit templates get TEMPLATE_ID

# Create a template from a JSON file
npx transloadit templates create my-template template.json

# Modify a template
npx transloadit templates modify TEMPLATE_ID template.json

# Rename a template
npx transloadit templates modify TEMPLATE_ID --name new-name

# Delete a template
npx transloadit templates delete TEMPLATE_ID

# Sync local template files with Transloadit (bidirectional)
npx transloadit templates sync templates/*.json
npx transloadit templates sync --recursive templates/

Billing

# Get bill for a month
npx transloadit bills get 2024-01

# Get detailed bill as JSON
npx transloadit bills get 2024-01 --json

Assembly Notifications

# Replay a notification
npx transloadit assembly-notifications replay ASSEMBLY_ID

# Replay to a different URL
npx transloadit assembly-notifications replay --notify-url https://example.com/hook ASSEMBLY_ID

Signature Generation

# Generate a signature for assembly params
echo '{"steps":{}}' | npx transloadit auth signature

# Generate with specific algorithm
echo '{"steps":{}}' | npx transloadit auth signature --algorithm sha256

# Generate a signed Smart CDN URL
echo '{"workspace":"my-workspace","template":"my-template","input":"image.jpg"}' | npx transloadit auth smart-cdn

CLI Options

All commands support these common options:

  • --json, -j - Output results as JSON (useful for scripting)
  • --log-level, -l - Set log verbosity level by name or number (default: notice)
  • --endpoint - Custom API endpoint URL (or set TRANSLOADIT_ENDPOINT env var)
  • --help, -h - Show help for a command

The assemblies create command additionally supports:

  • --single-assembly - Pass all input files to a single assembly instead of one assembly per file

Log Levels

The CLI uses syslog severity levels. Lower = more severe, higher = more verbose:

LevelValueDescription
err3Error conditions
warn4Warning conditions
notice5Normal but significant (default)
info6Informational messages
debug7Debug-level messages
trace8Most verbose/detailed

You can use either the level name or its numeric value:

# Show only errors and warnings
npx transloadit assemblies list -l warn
npx transloadit assemblies list -l 4

# Show debug output
npx transloadit assemblies list -l debug
npx transloadit assemblies list -l 7

SDK Usage

The following code will upload an image and resize it to a thumbnail:

import { Transloadit } from '@transloadit/node'

const transloadit = new Transloadit({
  authKey: 'YOUR_TRANSLOADIT_KEY',
  authSecret: 'YOUR_TRANSLOADIT_SECRET',
})

try {
  const options = {
    files: {
      file1: '/PATH/TO/FILE.jpg',
    },
    params: {
      steps: {
        // You can have many Steps. In this case we will just resize any inputs (:original)
        resize: {
          use: ':original',
          robot: '/image/resize',
          result: true,
          width: 75,
          height: 75,
        },
      },
      // OR if you already created a template, you can use it instead of "steps":
      // template_id: 'YOUR_TEMPLATE_ID',
    },
    waitForCompletion: true, // Wait for the Assembly (job) to finish executing before returning
  }

  const status = await transloadit.createAssembly(options)

  if (status.results.resize) {
    console.log('✅ Success - Your resized image:', status.results.resize[0].ssl_url)
  } else {
    console.log("❌ The Assembly didn't produce any output. Make sure you used a valid image file")
  }
} catch (err) {
  console.error('❌ Unable to process Assembly.', err)
  if (err instanceof ApiError && err.assemblyId) {
    console.error(`💡 More info: https://transloadit.com/assemblies/${err.assemblyId}`)
  }
}

You can find details about your executed Assemblies here.

Resuming interrupted uploads

If an upload was interrupted, you can resume it by providing the original assemblyUrl and the same input mapping. Resume relies on matching fieldname, filename, and size, so keep input names stable and pass the same files. Only path-based inputs resume; Buffer/string/stream uploads start a new tus upload automatically.

You can pass the same upload and progress options as createAssembly (such as chunkSize, uploadConcurrency, uploadBehavior, waitForCompletion, timeout, onUploadProgress, and onAssemblyProgress). When waitForCompletion is true, the SDK will poll and resolve once the Assembly is finished.

const status = await transloadit.resumeAssemblyUploads({
  assemblyUrl: 'https://api2.transloadit.com/assemblies/ASSEMBLY_ID',
  files: {
    file1: '/PATH/TO/FILE.jpg',
    file2: '/PATH/TO/FILE2.jpg',
  },
  uploadConcurrency: 2,
})

Examples

For more fully working examples take a look at examples/.

For more example use cases and information about the available robots and their parameters, check out the Transloadit website.

API

These are the public methods on the Transloadit object and their descriptions. The methods are based on the Transloadit API.

Table of contents:

Main

constructor(options)

Returns a new instance of the client.

The options object can contain the following keys:

  • authKey (required) - see requirements
  • authSecret (required) - see requirements
  • endpoint (default 'https://api2.transloadit.com')
  • maxRetries (default 5) - see Rate limiting & auto retry
  • gotRetry (default 0) - see Rate limiting & auto retry
  • timeout (default 60000: 1 minute) - the timeout (in milliseconds) for all requests (except createAssembly)
  • validateResponses (default false)

Assemblies

async createAssembly(options)

Creates a new Assembly on Transloadit and optionally upload the specified files and uploads.

You can provide the following keys inside the options object:

  • params (required) - An object containing keys defining the Assembly's behavior with the following keys: (See also API doc and examples)
    • steps - Assembly instructions - See Transloadit docs and demos for inspiration.
    • template_id - The ID of the Template that contains your Assembly Instructions. One of either steps or template_id is required. If you specify both, then any Steps will overrule the template.
    • fields - An object of form fields to add to the request, to make use of in the Assembly instructions via Assembly variables.
    • notify_url - Transloadit can send a Pingback to your server when the Assembly is completed. We'll send the Assembly Status in JSON encoded string inside a transloadit field in a multipart POST request to the URL supplied here.
  • files - An object (key-value pairs) containing one or more file paths to upload and use in your Assembly. The key is the field name and the value is the path to the file to be uploaded. The field name and the file's name may be used in the (Assembly instructions) (params.steps) to refer to the particular file. See example below.
    • 'fieldName': '/path/to/file'
    • more files...
  • uploads - An object (key-value pairs) containing one or more files to upload and use in your Assembly. The key is the file name and the value is the content of the file to be uploaded. Value can be one of many types:
    • 'fieldName': (Readable | Buffer | TypedArray | ArrayBuffer | string | Iterable<Buffer | string> | AsyncIterable<Buffer | string> | Promise).
    • more uploads...
  • waitForCompletion - A boolean (default is false) to indicate whether you want to wait for the Assembly to finish with all encoding results present before the promise is fulfilled. If waitForCompletion is true, this SDK will poll for status updates and fulfill the promise when all encoding work is done.
  • timeout - Number of milliseconds to wait before aborting (default 86400000: 24 hours).
  • onUploadProgress - An optional function that will be periodically called with the file upload progress, which is an with an object containing:
    • uploadedBytes - Number of bytes uploaded so far.
    • totalBytes - Total number of bytes to upload or undefined if unknown (Streams).
  • onAssemblyProgress - Once the Assembly has started processing this will be periodically called with the Assembly Execution Status (result of getAssembly) only if waitForCompletion is true.
  • chunkSize - (for uploads) a number indicating the maximum size of a tus PATCH request body in bytes. Default to Infinity for file uploads and 50MB for streams of unknown length. See tus-js-client.
  • uploadConcurrency - Maximum number of concurrent tus file uploads to occur at any given time (default 10.)
  • uploadBehavior - Controls how uploads are handled:
    • await (default) waits for all uploads to finish.
    • background starts uploads and returns once upload URLs are created.
    • none returns upload URLs without uploading any bytes.
    • When uploadBehavior is not await, waitForCompletion is ignored.

NOTE: Make sure the key in files and uploads is not one of signature, params or max_size.

When uploadBehavior is background or none, the resolved Assembly object includes upload_urls with a map of field names to tus upload URLs.

Example code showing all options:

await transloadit.createAssembly({
  files: {
    file1: '/path/to/file.jpg'
    // ...
  },
  uploads: {
    'file2.bin': Buffer.from([0, 0, 7]), // A buffer
    'file3.txt': 'file contents', // A string
    'file4.jpg': process.stdin // A stream
    // ...
  },
  params: {
    steps: { ... },
    template_id: 'MY_TEMPLATE_ID',
    fields: {
      field1: 'Field value',
      // ...
    },
    notify_url: 'https://example.com/notify-url',
  },
  waitForCompletion: true,
  timeout: 60000,
  onUploadProgress,
  onAssemblyProgress,
})

Example onUploadProgress and onAssemblyProgress handlers:

function onUploadProgress({ uploadedBytes, totalBytes }) {
  // NOTE: totalBytes may be undefined
  console.log(`♻️ Upload progress polled: ${uploadedBytes} of ${totalBytes} bytes uploaded.`)
}
function onAssemblyProgress(assembly) {
  console.log(
    `♻️ Assembly progress polled: ${assembly.error ? assembly.error : assembly.ok} ${
      assembly.assembly_id
    } ... `
  )
}

Tip: createAssembly returns a Promise with an extra property assemblyId. This can be used to retrieve the Assembly ID before the Assembly has even been created. Useful for debugging by logging this ID when the request starts, for example:

const promise = transloadit.createAssembly(options)
console.log('Creating', promise.assemblyId)
const status = await promise

See also:

async lintAssemblyInstructions(options)

Lint Assembly Instructions locally using the same linter as the API. If you provide a templateId, the template content is fetched and merged with your instructions before linting (matching the API's runtime merge behavior). If the template sets allow_steps_override=false, providing steps will throw TEMPLATE_DENIES_STEPS_OVERRIDE.

The options object accepts:

  • assemblyInstructions - Assembly Instructions as a JSON string, a full instructions object, or a steps-only object. If no steps property is present, the object is treated as steps.
  • templateId - Optional template ID to merge before linting.
  • fatal - 'error' | 'warning' (default: 'error'). When set to 'warning', warnings are treated as fatal.
  • fix - Apply auto-fixes where possible. If true, the result includes fixedInstructions.

The method returns:

  • success - true when no fatal issues are found.
  • issues - Array of lint issues (each includes code, type, row, column, and desc).
  • fixedInstructions - The fixed JSON string when fix is true (steps-only inputs return steps-only JSON).

Example:

const result = await transloadit.lintAssemblyInstructions({
  assemblyInstructions: {
    resize: { robot: '/image/resize', use: ':original', width: 100, height: 100 },
  },
  fatal: 'warning',
})

if (!result.success) {
  console.log(result.issues)
}

async listAssemblies(params)

Retrieve Assemblies according to the given params.

Valid params can be page, pagesize, type, fromdate, todate and keywords. Please consult the API documentation for details.

The method returns an object containing these properties:

  • items: An Array of up to pagesize Assemblies
  • count: Total number of Assemblies

streamAssemblies(params)

Creates an objectMode Readable stream that automates handling of listAssemblies pagination. It accepts the same params as listAssemblies.

This can be used to iterate through Assemblies:

const assemblyStream = transloadit.streamAssemblies({ fromdate: '2016-08-19 01:15:00 UTC' })

assemblyStream.on('readable', function () {
  const assembly = assemblyStream.read()
  if (assembly == null) console.log('end of stream')

  console.log(assembly.id)
})

Results can also be piped. Here's an example using through2:

const assemblyStream = transloadit.streamAssemblies({ fromdate: '2016-08-19 01:15:00 UTC' })

assemblyStream
  .pipe(
    through.obj(function (chunk, enc, callback) {
      this.push(chunk.id + '\n')
      callback()
    })
  )
  .pipe(fs.createWriteStream('assemblies.txt'))

async getAssembly(assemblyId)

Retrieves the JSON status of the Assembly identified by the given assemblyId. See API documentation.

async cancelAssembly(assemblyId)

Removes the Assembly identified by the given assemblyId from the memory of the Transloadit machines, ultimately cancelling it. This does not delete the Assembly from the database - you can still access it on https://transloadit.com/assemblies/{assembly_id} in your Transloadit account. This also does not delete any files associated with the Assembly from the Transloadit servers. See API documentation.

async replayAssembly(assemblyId, params)

Replays the Assembly identified by the given assemblyId (required argument). Optionally you can also provide a notify_url key inside params if you want to change the notification target. See API documentation for more info about params.

The response from the replayAssembly is minimal and does not contain much information about the replayed assembly. Please call getAssembly or awaitAssemblyCompletion after replay to get more information:

const replayAssemblyResponse = await transloadit.replayAssembly(failedAssemblyId)

const assembly = await transloadit.getAssembly(replayAssemblyResponse.assembly_id)
// Or
const completedAssembly = await transloadit.awaitAssemblyCompletion(
  replayAssemblyResponse.assembly_id
)

async awaitAssemblyCompletion(assemblyId, opts)

This function will continously poll the specified Assembly assemblyId and resolve when it is done uploading and executing (until result.ok is no longer ASSEMBLY_UPLOADING, ASSEMBLY_EXECUTING or ASSEMBLY_REPLAYING). It resolves with the same value as getAssembly.

opts is an object with the keys:

  • onAssemblyProgress - A progress function called on each poll. See createAssembly
  • timeout - How many milliseconds until polling times out (default: no timeout)
  • interval - Poll interval in milliseconds (default 1000)
  • signal - An AbortSignal to cancel polling. When aborted, the promise rejects with an AbortError.
  • onPoll - A callback invoked at the start of each poll iteration. Return false to stop polling early and resolve with the last known status. Useful for implementing custom cancellation logic (e.g., superseding assemblies in watch mode).

getLastUsedAssemblyUrl()

Returns the internal url that was used for the last call to createAssembly. This is meant to be used for debugging purposes.

Assembly notifications

async replayAssemblyNotification(assemblyId, params)

Replays the notification for the Assembly identified by the given assemblyId (required argument). Optionally you can also provide a notify_url key inside params if you want to change the notification target. See API documentation for more info about params.

Templates

Templates are Steps that can be reused. See example template code.

async createTemplate(params)

Creates a template the provided params. The required params keys are:

  • name - The template name
  • template - The template JSON object containing its steps

See also API documentation.

const template = {
  steps: {
    encode: {
      use: ':original',
      robot: '/video/encode',
      preset: 'ipad-high',
    },
    thumbnail: {
      use: 'encode',
      robot: '/video/thumbnails',
    },
  },
}

const result = await transloadit.createTemplate({ name: 'my-template-name', template })
console.log('✅ Template created with template_id', result.id)

async editTemplate(templateId, params)

Updates the template represented by the given templateId with the new value. The params works just like the one from the createTemplate call. See API documentation.

async getTemplate(templateId)

Retrieves the name and the template JSON for the template represented by the given templateId. See API documentation.

async deleteTemplate(templateId)

Deletes the template represented by the given templateId. See API documentation.

async listTemplates(params)

Retrieve all your templates. See API documentation for more info about params.

The method returns an object containing these properties:

  • items: An Array of up to pagesize templates
  • count: Total number of templates

streamTemplates(params)

Creates an objectMode Readable stream that automates handling of listTemplates pagination. Similar to streamAssemblies.

Template Credentials

Template Credentials allow you to store third-party credentials (e.g., AWS S3, Google Cloud Storage, FTP) securely on Transloadit for use in your Assembly Instructions.

async createTemplateCredential(params)

Creates a new Template Credential. The params object should contain the credential configuration. See API documentation.

async editTemplateCredential(credentialId, params)

Updates an existing Template Credential identified by credentialId. See API documentation.

async deleteTemplateCredential(credentialId)

Deletes the Template Credential identified by credentialId. See API documentation.

async getTemplateCredential(credentialId)

Retrieves the Template Credential identified by credentialId. See API documentation.

async listTemplateCredentials(params)

Lists all Template Credentials. See API documentation.

streamTemplateCredentials(params)

Creates an objectMode Readable stream that automates handling of listTemplateCredentials pagination. Similar to streamAssemblies.

Other

setDefaultTimeout(timeout)

Same as constructor timeout option: Set the default timeout (in milliseconds) for all requests (except createAssembly)

async getBill(date)

Retrieves the billing data for a given date string with format YYYY-MM. See API documentation.

calcSignature(params)

Calculates a signature for the given params JSON object. If the params object does not include an authKey or expires keys (and their values) in the auth sub-key, then they are set automatically.

This function returns an object with the key signature (containing the calculated signature string) and a key params, which contains the stringified version of the passed params object (including the set expires and authKey keys).

See Signature Generation in the CLI section for command-line usage.

getSignedSmartCDNUrl(params)

Constructs a signed Smart CDN URL, as defined in the API documentation. params must be an object with the following properties:

  • workspace - Workspace slug (required)
  • template - Template slug or template ID (required)
  • input - Input value that is provided as ${fields.input} in the template (required)
  • urlParams - Object with additional parameters for the URL query string (optional)
  • expiresAt - Expiration timestamp of the signature in milliseconds since UNIX epoch. Defaults to 1 hour from now. (optional)

Example:

const client = new Transloadit({ authKey: 'foo_key', authSecret: 'foo_secret' })
const url = client.getSignedSmartCDNUrl({
  workspace: 'foo_workspace',
  template: 'foo_template',
  input: 'foo_input',
  urlParams: {
    foo: 'bar',
  },
})

// url is:
// https://foo_workspace.tlcdn.com/foo_template/foo_input?auth_key=foo_key&exp=1714525200000&foo=bar&sig=sha256:9548915ec70a5f0d05de9497289e792201ceec19a526fe315f4f4fd2e7e377ac

Errors

Any errors originating from Node.js will be passed on and we use GOT v11 for HTTP requests. Errors from got will also be passed on, except the got.HTTPError which will be replaced with a transloadit.ApiError, which will have its cause property set to the instance of the original got.HTTPError. transloadit.ApiError has these properties:

  • code (string) - The Transloadit API error code.
  • rawMessage (string) - A textual representation of the Transloadit API error.
  • reason (string) - Additional information about the Transloadit API error.
  • assemblyId: (string) - If the request is related to an assembly, this will be the ID of the assembly.
  • assemblySslUrl (string) - If the request is related to an assembly, this will be the SSL URL to the assembly .

To identify errors you can either check its props or use instanceof, e.g.:

try {
  await transloadit.createAssembly(options)
} catch (err) {
  if (err instanceof got.TimeoutError) {
    return console.error('The request timed out', err)
  }
  if (err.code === 'ENOENT') {
    return console.error('Cannot open file', err)
  }
  if (err instanceof ApiError && err.code === 'ASSEMBLY_INVALID_STEPS') {
    return console.error('Invalid Assembly Steps', err)
  }
}

Note: Assemblies that have an error status (assembly.error) will only result in an error being thrown from createAssembly and replayAssembly. For other Assembly methods, no errors will be thrown, but any error can be found in the response's error property (also ApiError.code).

Rate limiting & auto retry

There are three kinds of retries:

Retry on rate limiting (maxRetries, default 5)

All functions of the client automatically obey all rate limiting imposed by Transloadit (e.g. RATE_LIMIT_REACHED), so there is no need to write your own wrapper scripts to handle rate limits. The SDK will by default retry requests 5 times with auto back-off (See maxRetries constructor option).

GOT HTTP retries (gotRetry, default { limit: 0 })

Because we use got under the hood, you can pass a gotRetry constructor option which is passed on to got. This offers great flexibility for handling retries on network errors and HTTP status codes with auto back-off. See got retry object documentation.

Note that the above maxRetries option does not affect the gotRetry logic.

Validate API responses (validateResponses, default false)

As we have ported the JavaScript SDK to TypeScript in v4, we are now also validating API responses using zod schemas. Having schema validation enabled (true), guarantees that the data returned by the SDK adheres to the TypeScript types of this SDK. However we are still working on improving the schemas and they are not yet 100% complete. This means that if you hit a bug in the schemas, a zod schema validation error will be thrown. If you encounter such an error, please report it and we will fix it as soon as possible. If you set this option to false, schema validation will be disabled, and you won't get any such errors, however the TypeScript types will not protect you should such a bug be encountered.

Custom retry logic

If you want to retry on other errors, please see the retry example code.

Debugging

This project uses debug so you can run node with the DEBUG=transloadit evironment variable to enable verbose logging. Example:

DEBUG=transloadit* node examples/template_api.ts

Maintainers

Changelog

See Releases

Attribution

Thanks to Ian Hansen for donating the transloadit npm name. You can still access his code under v0.0.0.

License

MIT © Transloadit

Development

See CONTRIBUTING.

Keywords

transloadit

FAQs

Package last updated on 23 Apr 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts