Skip to content

SDKs and components

SurgeMedia is API-first: everything the admin does with media, your code can do through the REST API v1. The official front-end packages reduce the most common integrations (responsive images, videos, uploads, pickers) to a few lines of code.

Package For License Status
@surge-media/core Server: admin, REST API, delivery, processing BUSL-1.1 Available
@surge-media/client Any JavaScript runtime: browser, Node.js, edge MIT In development (first release: 0.1)
@surge-media/vue Vue 3.5+, including Nuxt MIT In development (first release: 0.1)
@surge-media/nuxt Nuxt module (auto-imports, token route) MIT Later. Nuxt already works with @surge-media/vue
@surge-media/react React, Next.js MIT Planned
@surge-media/svelte Svelte, SvelteKit MIT Planned

The display components (images, <picture>, videos, thumbnails, processing status) and uploads are ready; media pickers and editing (focal point, crop, poster, subtitles) will follow before the first release. To get notified, watch releases on the GitHub repository.

Terminal window
npm install @surge-media/vue

@surge-media/client is installed with it. Vue 3.5 or later is required.

Register the plugin once, with your instance URL, the project ID and a credential:

main.ts
import { createSurgeMedia } from '@surge-media/vue'
import '@surge-media/vue/style.css' // optional theme
app.use(createSurgeMedia({
baseUrl: 'https://media.example.com',
projectId: 'cm…',
publishableKey: 'sm_pk_…',
locale: 'en', // 'fr' by default; a ref follows your app's language
}))
Credential Use it for
No credential Displaying Media objects your back end already fetched (public media, or private media with their signed URLs).
Publishable key (publishableKey) Public sites: public media, listing when the project enables it. Restricted to the project’s allowed origins.
Delegated tokens (getToken) Signed-in users: private media, uploads, and later editing. Your back end issues short-lived tokens with its secret key; the client renews them before they expire. Include project:read in their scopes.

Never put a secret key or a personal token in a browser: the client refuses them and the API rejects them (SECRET_IN_BROWSER).

<script setup lang="ts">
import type { Media } from '@surge-media/client'
import { SmImage, SmPicture, SmVideo } from '@surge-media/vue'
defineProps<{ hero: Media; gallery: Media[]; trailer: Media }>()
</script>
<template>
<!-- Fluid image: srcset with the real width of each file -->
<SmImage :media="hero" sizes="(min-width: 960px) 50vw, 100vw" priority />
<!-- Fixed size with a 16:9 crop around the focal point: 1x, 2x, 3x -->
<SmImage
v-for="item in gallery" :key="item.id"
:media="item" :width="320" aspect="16/9"
/>
<!-- AVIF, WebP and JPEG; a square crop on small screens -->
<SmPicture
:media="hero"
:sources="[{ media: '(max-width: 640px)', aspect: 1 }]"
/>
<!-- Native player: AV1, H.264 or original sources, poster, captions -->
<SmVideo :media="trailer" />
</template>
Component What it does
SmImage <img> with a srcset by width (or by density with a fixed width), width / height always set (no layout shift), server crop around the focal point (aspect, fit), presets (preset, presets), loading, fetchpriority or priority, objectFit to fill a box. Alternative text from alt or the media; decorative for purely decorative images.
SmPicture <picture> with one <source> per format enabled on the server (AVIF, WebP) and a JPEG fallback; art direction through sources (a crop per media query).
SmVideo The browser’s native player with the server’s playback sources, a sized poster, text tracks, lazy loading. No autoplay: ambient loops a muted video with a pause button. While the server is preparing a video, it shows its status and a link to the original.
SmMedia Picks SmImage or SmVideo from the media kind.
SmThumbnail Square thumbnail cropped around the focal point, video duration, processing badge.
SmProcessingStatus Processing status of a video, with a progress bar and polite announcements for screen readers.
SmUploader Uploads images and videos with delegated tokens: native file input, drag and drop, paste, checks before sending, progress, cancel, retry, poster capture (see Upload files).

The components follow the project’s transformation policy: with presets only, they build their srcset from presets; with signed only, from presets too, unless the media is private (its URLs are already signed). If a derivative fails to load, the image falls back to the original file, then to its alternative text.

useMedia(id) loads a media item in the browser, refreshes the signed URLs of a private one before they expire, and follows the processing of a video until it is ready.

SmUploader sends images and videos to the project with delegated tokens that include the media:upload scope (see below):

<script setup lang="ts">
import type { Media } from '@surge-media/client'
import { SmUploader } from '@surge-media/vue'
function onUploaded(media: Media) {
// Store media.id with your content
}
</script>
<template>
<SmUploader :kinds="['image']" details @uploaded="onUploaded" />
</template>
  • Checked before sending: accepted types, maximum size per type and uploads left come from the token (GET /me); a refused file is explained at once, such as “This file is too large. Maximum size: 25 MB.” The server still checks the contents.
  • Queue: two uploads at a time, progress per file, cancel, retry; automatic retry after a 429, a 503 or a network error, 3 times at most.
  • Videos: a poster frame is captured in the browser during the upload, then attached to the video.
  • details: the title and alternative text are entered before the upload, because an upload token cannot edit a media item afterwards. Without it, files leave as soon as they are chosen.
  • visibility, chooseVisibility and folderId set where files go, unless the token enforces them; capture (user or environment) opens the camera on phones. Events: uploaded, error, done.
  • Accessible: a native file input with a visible button (drag and drop and paste only add to it), constraints linked to the input, one announcement per finished file.

Your back end issues the tokens with the project’s secret key, through the server entry of the client. Add @surge-media/client to your dependencies, with the same version as @surge-media/vue:

// server.ts — Node.js with Express
import express from 'express'
import {
createDelegatedToken,
UPLOAD_SCOPES,
} from '@surge-media/client/server'
const app = express()
app.post('/api/surge-media/token', async (req, res) => {
const user = req.user // your own authentication
if (!user) return res.sendStatus(401)
res.json(await createDelegatedToken({
baseUrl: process.env.SURGE_MEDIA_URL!,
projectId: process.env.SURGE_MEDIA_PROJECT!,
secretKey: process.env.SURGE_MEDIA_SECRET_KEY!,
scopes: UPLOAD_SCOPES, // project:read, media:read, media:upload
subject: String(user.id),
origin: 'https://www.example.com',
// Optional: types, visibility, folderId
upload: { maxFiles: 10, maxSize: 50 * 1024 * 1024 },
}))
})

The plugin then gets its tokens from this route: getToken: () => fetch('/api/surge-media/token', { method: 'POST' }).then(r => r.json()). @surge-media/client/server refuses to run in a browser; the main entry never imports it. maxFiles counts per token: a renewed token starts again from zero, so keep any per-user quota in your application.

From another language, call the API directly:

Terminal window
curl -X POST \
"https://media.example.com/api/v1/projects/cm…/delegated-tokens" \
-H "Authorization: Bearer $SURGE_MEDIA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"scopes":["project:read","media:read","media:upload"]}'
  • @surge-media/vue/style.css, the client’s theme (@surge-media/client/style.css) reused as is, is optional: without it, sizes, aspect ratios and screen reader texts stay correct. It defines --sm-* tokens (--sm-color-primary, --sm-color-surface, --sm-radius…) for light and dark modes. Dark mode follows the system preference unless an ancestor has .light or [data-theme="light"], and always applies when an ancestor has .dark or [data-theme="dark"]. Everything lives in the surge-media CSS layer, so your styles always win.
  • French (default) and English are built in. Pass locale (a string or a ref) and override or add texts with messages: { en: { video: { download: 'Download' } } }.
  • The components target WCAG 2.2 AA: native elements, keyboard access, no autoplay, contrast checked in both themes.

This is the framework-free layer the components are built on. Use it directly in plain JavaScript, on a server or in another framework:

import {
createSurgeClient,
srcsetAttribute,
widthCandidates,
} from '@surge-media/client'
const client = createSurgeClient({
baseUrl: 'https://media.example.com',
projectId: 'cm…',
publishableKey: 'sm_pk_…',
})
const { items } = await client.media.list({ kind: 'image', limit: 12 })
// Filter by tag slugs: at least one by default, or all of them with tagMatch: 'all'
const heroes = await client.media.list({ tags: ['hero', 'summer'], tagMatch: 'all' })
// Transformation policy, enabled formats, maximum size
const project = await client.project()
const srcset = srcsetAttribute(widthCandidates(items[0], {
widths: [480, 960, 1440],
format: 'avif',
maxDimension: project.transformMaxDimension,
}))

It handles ETag revalidation, delegated token renewal and translated errors (SurgeApiError), and builds canonical transformation URLs in the exact form the server expects, which avoids a redirect. imageSourceSet() computes all the attributes of an image (src, srcset, sizes, width, height) from the project’s policy, and imageSource() derives them from a component’s props and the project settings: it is the heart of every image component.

For uploads, client.media.upload() sends a file (with progress in browsers), client.uploadRules() reads the rules of the token, checkFile() and acceptAttribute() apply them, and createUploadQueue() is the framework-free queue behind SmUploader. On your server, @surge-media/client/server issues delegated tokens.

The component logic lives in the client too, shared by every library: the project’s display settings (displaySettings()), alternative text and image fallback (resolveAltText(), nextImageStage()), the <source> tags of a <picture> (pictureSources()), poster, messages and retries of a video (videoPoster(), heldVideoDelay()), processing status, upload display, French and English texts (createTranslate()), icons (ICONS) and inline styles (cssText() for frameworks that take text styles). So does the theme: @surge-media/client/style.css (sm-* classes, --sm-* tokens). @surge-media/vue only adds rendering and reactivity.

No package for your framework yet (Angular, SolidJS, Qwik…)? Build a framework integration on top of the client and its theme, the way the official packages are built.

The API is described by an OpenAPI 3.1 document served by your instance at /api/v1/openapi.json (?lang=en or fr). Generate a typed client with the tool of your choice. For example, in TypeScript:

Terminal window
npx openapi-typescript https://media.example.com/api/v1/openapi.json \
-o surge-media.d.ts

Image URLs need no SDK at all: replace {transform} and {format} in a media item’s urlTemplate (see Image transformations).

@surge-media/vue works in Nuxt (with Vue 3.5 or later) and its server-side rendering: a Nuxt plugin runs once per request on the server, which is exactly what the library needs (delegated tokens belong to one visitor). A dedicated @surge-media/nuxt module may come later; nothing below will need to change.

Terminal window
npm install @surge-media/vue
nuxt.config.ts
export default defineNuxtConfig({
css: ['@surge-media/vue/style.css'], // optional theme
runtimeConfig: {
SurgeMedia: {
// NUXT_SURGE_MEDIA_SECRET_KEY — server only (step 3)
secretKey: '',
},
public: {
SurgeMedia: {
baseUrl: '', // NUXT_PUBLIC_SURGE_MEDIA_BASE_URL
projectId: '', // NUXT_PUBLIC_SURGE_MEDIA_PROJECT_ID
publishableKey: '', // NUXT_PUBLIC_SURGE_MEDIA_PUBLISHABLE_KEY
},
},
},
})

Set these variables (NUXT_PUBLIC_SURGE_MEDIA_BASE_URL: your instance address, such as https://media.example.com), then add your site’s origin (https://www.example.com) to the project’s allowed origins in the SurgeMedia admin.

plugins/surge-media.ts
import {
createSurgeMedia,
SmImage,
SmMedia,
SmPicture,
SmThumbnail,
SmUploader,
SmVideo,
} from '@surge-media/vue'
export default defineNuxtPlugin((nuxtApp) => {
const { SurgeMedia } = useRuntimeConfig().public
nuxtApp.vueApp.use(createSurgeMedia({
baseUrl: SurgeMedia.baseUrl,
projectId: SurgeMedia.projectId,
publishableKey: SurgeMedia.publishableKey,
// With @nuxtjs/i18n: locale: nuxtApp.$i18n.locale
locale: 'en',
// Presets-only or signed policy, or restricted formats? Say so here:
// the server render then builds the right URLs from the start.
// defaults: { policy: 'presets', formats: ['webp', 'jpg'] },
}))
// Available in every page and component, without imports.
const components = {
SmImage, SmPicture, SmVideo, SmMedia, SmThumbnail, SmUploader,
}
for (const [name, component] of Object.entries(components)) {
nuxtApp.vueApp.component(name, component)
}
})

Then use the components anywhere, with media fetched on the server so the page is rendered complete:

pages/index.vue
<script setup lang="ts">
const config = useRuntimeConfig().public.SurgeMedia
const { data: hero } = await useFetch(
`${config.baseUrl}/api/v1/projects/${config.projectId}/media/cm…`,
{ headers: { Authorization: `Bearer ${config.publishableKey}` } },
)
</script>
<template>
<SmImage v-if="hero" :media="hero" sizes="100vw" priority />
</template>

3. Private media and uploads: delegated tokens (optional)

Section titled “3. Private media and uploads: delegated tokens (optional)”

To show private media to signed-in visitors or let them upload files, let your Nuxt server issue delegated tokens with the project’s secret key, which never leaves the server. Add @surge-media/client (same version as @surge-media/vue) for its server entry:

server/api/surge-media/token.post.ts
import {
createDelegatedToken,
UPLOAD_SCOPES,
} from '@surge-media/client/server'
export default defineEventHandler(async (event) => {
// Your own authentication: only signed-in visitors get a token
// (requireUserSession comes from nuxt-auth-utils, for example).
const { user } = await requireUserSession(event)
const config = useRuntimeConfig(event)
const { baseUrl, projectId } = config.public.SurgeMedia
// Returns { token, expiresAt, scopes }, accepted as is by the plugin.
return createDelegatedToken({
baseUrl,
projectId,
secretKey: config.SurgeMedia.secretKey,
// DISPLAY_SCOPES to show private media without uploads
scopes: UPLOAD_SCOPES,
subject: String(user.id),
})
})

In the plugin, replace publishableKey with getToken:

plugins/surge-media.ts
// Forwards the visitor's cookies during server rendering
const requestFetch = useRequestFetch()
nuxtApp.vueApp.use(createSurgeMedia({
baseUrl: SurgeMedia.baseUrl,
projectId: SurgeMedia.projectId,
getToken: () =>
requestFetch('/api/surge-media/token', { method: 'POST' }),
}))

The client asks for a token on first use and renews it before it expires. Because the plugin runs for each request, two visitors never share a token.