@uploadcare/signed-uploads secures uploads to Uploadcare's Signed Uploads feature. It has two halves:
@uploadcare/signed-uploads — Node only. Mints the credentials the Upload API accepts: a JWT for the Authorization: Bearer scheme (with optional endpoint scope and operation limits), or the signature and expire pair. Both need your project secret key, so both belong on your server.@uploadcare/signed-uploads/client — browser-first, and runs in Node too. Caches a token minted by your server and replaces it before it expires. Never touches the secret key.Zero dependencies, full TypeScript support.
npm install @uploadcare/signed-uploads
NOTE: The Uploadcare API accepts expire as unix time in seconds. However, this library accepts time in milliseconds, as per the Node.js standard.
import { generateAuthToken } from '@uploadcare/signed-uploads'
// In your endpoint, e.g. GET /uploadcare-token
const token = generateAuthToken('YOUR_SECRET_KEY', {
lifetime: 60 * 30 * 1000 // expire in 30 minutes, 24 hours max
})
Tokens can be restricted to the endpoints they reach and the number of operations they allow:
const token = generateAuthToken('YOUR_SECRET_KEY', {
lifetime: 60 * 30 * 1000,
// Exact paths, or a trailing `*` after a `/` as a whole-segment prefix.
// Omit to allow every signed endpoint.
scope: ['/base/', '/multipart/*'],
// 1 to 100000
operations: 20
})
Anything the Upload API would refuse — a lifetime over 24 hours, a malformed scope item, an out-of-range operation count — throws here instead, so the mistake surfaces on your server rather than as a 403 in someone's browser.
AuthTokenCache fetches a token from your endpoint, holds it, and replaces it shortly before it expires. Pass getToken straight to @uploadcare/upload-client, which calls it before every request:
import { AuthTokenCache } from '@uploadcare/signed-uploads/client'
import { uploadFile } from '@uploadcare/upload-client'
const tokens = new AuthTokenCache({
fetchToken: async () => {
const response = await fetch('/uploadcare-token')
return (await response.json()).token
}
})
await uploadFile(file, {
publicKey: 'YOUR_PUBLIC_KEY',
authToken: tokens.getToken
})
Concurrent callers share a single request rather than each starting their own.
With SSR, hand the cache a token you already minted while rendering, so the first upload needs no round-trip:
const tokens = new AuthTokenCache({
fetchToken,
initialToken: tokenRenderedIntoThePage
})
AuthTokenCache runs in Node as well as the browser (it needs only atob and
TextDecoder). Be careful with it on a server: a module-level cache is shared
by every request the process handles, so a token minted for one visitor would be
served to the next. If your tokens carry per-user claims such as sub, build
the cache per request — or mint the token directly with generateAuthToken,
which is what the server has the secret key for.
With React, keep one long-lived cache and reassign fetchToken rather than building a new cache. A component passes a new closure on every render, and rebuilding would throw the token away each time:
tokens.fetchToken = props.fetchToken // cached token is kept
tokens.invalidate() // call this when the change is real, e.g. on sign-out
If your fetchToken throws, rejects, or returns no token (undefined, null
or ''), getToken() rejects with an AuthTokenResolverError carrying the
original failure on cause. Nothing is cached, so the next call tries again:
import { AuthTokenResolverError } from '@uploadcare/signed-uploads/client'
try {
await tokens.getToken()
} catch (error) {
if (error instanceof AuthTokenResolverError) {
// your token endpoint failed; `error.cause` says how
}
}
@uploadcare/upload-client throws the same class when you pass it a token
function directly, and re-exports it.
To authenticate your own requests, getAuthHeaders builds the header and returns {} for an absent token, so it can be spread unconditionally:
import { getAuthHeaders } from '@uploadcare/signed-uploads/client'
fetch(url, { headers: { ...getAuthHeaders(await tokens.getToken()) } })
import { generateSecureSignature } from '@uploadcare/signed-uploads'
// by the expiration timestamp in milliseconds since the epoch
const { secureSignature, secureExpire } = generateSecureSignature(
'YOUR_SECRET_KEY',
{
expire: Date.now() + 60 * 30 * 1000 // expire in 30 minutes
}
)
// by the expiration date
const { secureSignature, secureExpire } = generateSecureSignature(
'YOUR_SECRET_KEY',
{
expire: new Date('2099-01-01') // expire on 2099-01-01
}
)
// by the lifetime in milliseconds
const { secureSignature, secureExpire } = generateSecureSignature(
'YOUR_SECRET_KEY',
{
lifetime: 60 * 30 * 1000 // expire in 30 minutes
}
)
A pair of secureSignature and secureExpire (string with a unixtime in seconds) can be passed directly to the corresponding options of @uploadcare/upload-client.
If you think you ran into something in Uploadcare libraries that might have security implications, please hit us up at bugbounty@uploadcare.com or Hackerone.
We'll contact you personally in a short time to fix an issue through co-op and prior to any public disclosure.
Issues and PRs are welcome. You can provide your feedback or drop us a support request at hello@uploadcare.com.