tiny.pictures-js
v6.0.0
Published
Image URLs, responsive srcsets and lazy loading for the tiny.pictures image CDN — with a Next.js image loader, a Nuxt Image provider and a server-side API client. No dependencies.
Maintainers
Readme
tiny.pictures-js
The JavaScript library for tiny.pictures, the image CDN
that resizes, crops and converts your images on the fly. It builds image URLs
and responsive srcsets, lazy-loads images in the browser, plugs into
next/image and Nuxt Image, and talks to the tiny.pictures API from your
server.
- No dependencies. 27 kB minified for the script tag, lazy loader included; the URL builder alone is a fraction of that.
- Every runtime. Node.js 20+, Deno, Bun, edge runtimes and browsers. ES modules and CommonJS, with TypeScript types for both.
- Framework-ready. A loader for
next/image, a provider for Nuxt Image, and a plain URL builder for unpic, Astro, Angular and anything else. - Typed parameters.
width,format,gravityand every other operation autocomplete in your editor.
import TinyPictures from "tiny.pictures-js"
const tinyPictures = new TinyPictures({
user: "demo",
namedSources: [{ name: "main", url: "https://tiny.pictures/" }],
})
tinyPictures.url("https://tiny.pictures/example1.jpg", { width: 400, format: "best" })
// → https://demo.tiny.pictures/main/example1.jpg?width=400&format=bestContents
- Installation
- Image URLs
- Lazy loading in the browser
- Next.js (
next/image) - Nuxt Image
- Other frameworks
- On your server: API client and signed URLs
- API reference
- Upgrading
Installation
npm install tiny.pictures-jsOr load the browser build from a CDN, which defines a global TinyPictures:
<script src="https://cdn.jsdelivr.net/npm/tiny.pictures-js@6/dist/browser.js"></script>| Import | What you get |
| --- | --- |
| tiny.pictures-js | The TinyPictures class: URLs, srcsets, <img> markup. No DOM. |
| tiny.pictures-js/browser | The same class plus lazy loading and <picture> wrapping. |
| tiny.pictures-js/url | The URL builder as plain functions, tree-shakable. |
| tiny.pictures-js/next | A loader for next/image. |
| tiny.pictures-js/nuxt-image | A provider for Nuxt Image. |
| tiny.pictures-js/server | API client and URL signing. Server only. |
Image URLs
Create one instance with your account name, and with the named sources you set up in the dashboard:
import TinyPictures from "tiny.pictures-js"
const tinyPictures = new TinyPictures({
user: "demo",
namedSources: [{ name: "main", url: "https://www.example.com/" }],
})url(source, options) turns the URL of an original image into a tiny.pictures
URL. An image under a named source is addressed by name and path; any other
image travels in the source parameter.
tinyPictures.url("https://www.example.com/photos/beach.jpg", {
width: 800,
height: 600,
resizeType: "cover",
gravity: "attention",
format: "best",
})
// → https://demo.tiny.pictures/main/photos/beach.jpg?width=800&height=600&resizeType=cover&gravity=attention&format=best
tinyPictures.url("https://elsewhere.example.org/cat.png", { width: 200 })
// → https://demo.tiny.pictures/?width=200&source=https%3A%2F%2Felsewhere.example.org%2Fcat.pngformat: "best" serves AVIF or WebP to the browsers that support them, and the
original format to the rest, each at a quality that suits the format.
For responsive images, srcset() builds one candidate per width:
const tinyPictures = new TinyPictures({ user: "demo", srcsetWidths: [400, 800, 1200] })
const src = "https://tiny.pictures/example1.jpg"
const html = `<img src="${tinyPictures.url(src, { width: 800 })}"
srcset="${tinyPictures.srcset(src, { format: "best" })}"
sizes="(min-width: 800px) 50vw, 100vw" alt="">`The same URL in a different spelling is a different image to a CDN cache, so the library writes every URL the same way, however its input was written: the same source and options always give the same URL, byte for byte.
Lazy loading in the browser
The browser build loads images when they come into view, picks the right width
for each one, and adds a WebP candidate in a <picture> element:
<img class="tp-lazyload"
data-tp-src="https://www.example.com/photos/beach.jpg"
data-tp-sizes="auto"
data-tp-options='{"quality": 70}'
alt="Beach">
<script src="https://cdn.jsdelivr.net/npm/tiny.pictures-js@6/dist/browser.js"></script>
<script>
const tinyPictures = new TinyPictures({
user: "demo",
namedSources: [{ name: "main", url: "https://www.example.com/" }],
})
tinyPictures.lazyload()
</script>With a bundler, import tiny.pictures-js/browser instead of the script tag.
| Attribute or class | Effect |
| --- | --- |
| class="tp-lazyload" | Load the image lazily. It gets tp-lazyloading while loading and tp-lazyloaded when done. |
| data-tp-src | The original image, absolute or relative to the page. |
| data-tp-sizes | Adds a srcset: auto computes sizes from the rendered width, anything else is used as sizes. |
| data-tp-options | Transformation parameters as JSON. |
| class="tp-lazypreload" | Load the image soon, even outside the viewport. |
| tp-nopicture (attribute or class) | Leave the image as it is, without a <picture> around it. |
Each image is wrapped in a <picture> with a WebP <source> before it loads.
Cancel the tpbeforewrapinpicture event to keep a particular image out of it:
document.addEventListener("tpbeforewrapinpicture", (event) => {
if (event.target.closest(".gallery")) event.preventDefault()
})reveal(element) loads one image now, revealAll() all of them.
lazySizesConfig in the options changes the class and attribute names; the
lazy loader is lazysizes, bundled.
Next.js (next/image)
// tiny-pictures-loader.ts
"use client"
import { createNextImageLoader } from "tiny.pictures-js/next"
export default createNextImageLoader({
user: "demo",
namedSource: "main", // the named source that points to your website
})// next.config.js
module.exports = {
images: { loader: "custom", loaderFile: "./tiny-pictures-loader.ts" },
}<Image src="/photos/beach.jpg" width={800} height={600} sizes="50vw" alt="Beach" />Every srcset candidate is a tiny.pictures URL with format=best. Relative
paths are read as paths in namedSource; absolute URLs go through their own
named source (namedSources) or the source parameter. defaults adds
parameters to every image, for example { gravity: "attention" }. Next.js's own
optimizer is no longer involved, so this works on any hosting.
Nuxt Image
// nuxt.config.ts
export default defineNuxtConfig({
modules: ["@nuxt/image"],
image: {
provider: "tinyPictures",
providers: {
tinyPictures: {
provider: "tiny.pictures-js/nuxt-image",
options: { user: "demo", namedSource: "main" },
},
},
},
})The same configuration works with Nuxt Image 1 and 2.
<NuxtImg src="/photos/beach.jpg" width="400" height="400" :modifiers="{ gravity: 'attention' }" />
<NuxtPicture src="/photos/beach.jpg" format="avif,webp" width="800" sizes="100vw md:50vw" />fit becomes resizeType, and both dimensions together crop to the box.
Without a format the browser gets the best one it accepts; <NuxtPicture>'s
AVIF and WebP sources each get a quality that suits the format. Any other
modifier is passed on as a tiny.pictures parameter.
Other frameworks (unpic, Astro, Angular, …)
tiny.pictures-js/url is the URL builder as a function, for any component that
takes a loader or transformer:
import { createUrlBuilder } from "tiny.pictures-js/url"
const imageUrl = createUrlBuilder({ user: "demo", namedSource: "main" })
imageUrl("/photos/beach.jpg", { width: 400, height: 400 })
// → https://demo.tiny.pictures/main/photos/beach.jpg?width=400&height=400&resizeType=cover&format=bestLike the framework helpers it crops when both dimensions are given, asks for
format=best unless you name a format (null keeps the original's), and picks
a quality per format. rawImageUrl() and srcset() apply no defaults. Ready-made
snippets for unpic, Astro and Angular:
Image CDN loaders for frameworks.
On your server: API client and signed URLs
Keep your API token and signing secrets secret. They give access to your account. Use them on a server only: never in browser code, never in a
NEXT_PUBLIC_,NUXT_PUBLIC_orVITE_variable, never in a repository. Read them from your server's environment.tiny.pictures-js/serverrefuses to run in a browser for this reason.
API client
Create an API token in the dashboard (Tools → API tokens) and put it into the
TINY_PICTURES_API_TOKEN environment variable of your server:
import { createTinyPicturesClient } from "tiny.pictures-js/server"
const client = createTinyPicturesClient() // reads TINY_PICTURES_API_TOKEN
// a TinyPictures instance with your account's named sources, fetched once and
// cached for five minutes
const tinyPictures = await client.createTinyPictures({ srcsetWidths: [400, 800] })
tinyPictures.url("https://www.example.com/photos/beach.jpg", { width: 400 })
await client.getIntegration() // { user, namedSources: [{ name, url, signingEnabled }] }
await client.getPresets() // [{ name, parameters, whitelist }]
await client.purge(["/main/photos/beach.jpg"]) // remove from the CDN cache
await client.purgeAll()Named sources come back as name, URL and signing flag only. Origin credentials
configured on a source never leave the API client, so its answers are safe to
pass on to your pages. Errors are TinyPicturesApiErrors with the HTTP
status; a rate-limited request is retried once after Retry-After.
| Option | Default | |
| --- | --- | --- |
| token | process.env.TINY_PICTURES_API_TOKEN | The API token. |
| baseUrl | https://tiny.pictures | Where the API is. |
| fetch | global fetch | For tests, proxies or instrumentation. |
| timeoutMs | 30000 | Per request. |
| cacheTtlMs | 300000 | How long getIntegration() is reused. |
Signed URLs
A named source can require signed URLs, so that nobody but you can request new transformations of its images. Sign each URL on your server with the source's signing secret from the dashboard:
import { signUrl } from "tiny.pictures-js/server"
const signed = await signUrl(tinyPictures.url(source, { width: 400 }), {
user: "demo",
secret: process.env.TINY_PICTURES_SIGNING_SECRET,
})
// → https://demo.tiny.pictures/main/photos/beach.jpg?width=400&signature=…Request the signed URL exactly as it is; any change to it invalidates the
signature. signUrl uses Web Crypto, so it works in Node.js, Deno, Bun and edge
runtimes.
API reference
new TinyPictures(options)
| Option | Type | Default | |
| --- | --- | --- | --- |
| user | string | — | Your account name. Required. |
| namedSources | { name, url }[] | [] | Your named sources. The first whose URL a source starts with is used. |
| customSubdomain | boolean \| string | true | true: https://<user>.tiny.pictures/. false: https://tiny.pictures/api/<user>/. A string: a base URL the user name is appended to. |
| apiBaseUrl | string | — | A complete base URL, user included, such as a custom hostname. Overrides customSubdomain and protocol. |
| protocol | string | "https" | |
| defaultBaseUrl | string | "" (the page in the browser) | What relative sources are resolved against. |
| srcsetWidths | number[] | 50 … 3024 | The widths srcset candidates are built for. |
| overrideSourcesImages | boolean \| string \| string[] | [] | Stand-in images for sources on private hosts such as localhost, which tiny.pictures cannot fetch: a URL, a list of URLs, true for a random photo, or a category name ("cats", "nature", …). |
| overrideSourcesAlways | boolean | false | Use the stand-in images for every source. |
| lazySizesConfig | object | | Lazy loader options. Browser build only. |
Methods
| Method | Returns | |
| --- | --- | --- |
| url(source, options?, baseUrl?) | string \| null | The image URL; null for an empty source. Throws for a relative source without a base URL. |
| srcset(source, options?) | string | The srcset attribute value. |
| srcsetArray(source, options?) | string[] | The srcset candidates. |
| image(source, options?, attributes?, originalWidth?) | string | An <img> tag; with originalWidth, including a srcset. Attribute values are HTML-escaped. |
| lazyload() | | Browser: start lazy loading. |
| reveal(element), revealAll() | | Browser: load images now. |
The transformation parameters (options) are documented at
tiny.pictures/documentation/operations.
The TypeScript type ImageOptions knows all of them and accepts any other
parameter, too.
Upgrading
See the changelog. In short, from 5.x to 6.0: nothing to do for URLs, which stay exactly the same; the package has no dependencies any more, and it is MIT licensed.
Links
- Documentation: https://tiny.pictures/documentation/js-library
- Image operations: https://tiny.pictures/documentation/operations
- Support: https://tiny.pictures/contact
License
MIT © Tiny Tools Microservices GmbH
