The Uniform redirect SDK

The Uniform SDK lets developers work with redirects.

The following example is a platform-agnostic approach to executing on redirects using the Uniform redirect SDK.

import { RedirectClient, WithMemoryCache } from '@uniformdev/redirect' import * as dotenv from 'dotenv' dotenv.config() const client = new RedirectClient({ apiKey: process.env.UNIFORM_API_KEY, projectId: process.env.UNIFORM_PROJECT_ID, // Store a cache of the data needed to resolve redirects in memory. This could potentially get large. // Can operate without it, but will request data every hit. Also of note the API is cached by fastly, so the repeated request response will be fast. // Memory cache only makes sense in middleware environments that retain objects between requests somehow. dataCache: new WithMemoryCache({ prePopulate: true, refreshRate: 20000 }), }) // Expected that whatever product is being used has the ability get get the current URL and perform a redirect. export default async function middleware(request: { getUrl: () => string, redirect: (target: string, statusCode: number) => void, keepGoingNormally: () => void, }) { const url = request.getUrl() const result = await client.processUrlBestMatch(url) if (result) { request.redirect( result.url, result.definition?.redirect.targetStatusCode ?? 301 ) return } request.keepGoingNormally() }

The following examples represent converting Uniform redirects into a format that's executable by third-party hosting tools such as Netlify and Cloudflare:

import { RedirectClient } from '@uniformdev/redirect' import * as dotenv from 'dotenv' import * as fs from 'fs' const convertUniformToNextjs = async () => { dotenv.config() const client = new RedirectClient({ apiKey: process.env.UNIFORM_API_KEY, projectId: process.env.UNIFORM_PROJECT_ID, }) const ret = [] let redirects = (await client.getRedirects({ limit: 50, offset: 0 })) .redirects let count = 0 while (redirects.length) { const redirect = redirects.pop() ret.push({ source: redirect?.redirect.sourceUrl, destination: redirect?.redirect.targetUrl, permanent: redirect?.redirect.targetStatusCode === 301, }) if (!redirects.length) { count++ redirects = (await client.getRedirects({ limit: 50, offset: count * 50 })) .redirects } } if (!fs.existsSync('out')) { fs.mkdirSync('out') } fs.writeFile( 'out/nextJsRedirects.json', JSON.stringify(ret, undefined, ' '), (e) => { if (e) { console.log(e) } } ) } convertUniformToNextjs()

The previous examples of converting Uniform redirects result in an output like the following:

[ { "source": "/a", "destination": "/b", "permanent": true }, { "source": "/this", "destination": "/that", "permanent": true }, { "source": "/product/electronics/walkie-talkie", "destination": "/electronics/walkie-talkie", "permanent": true }, { "source": "/source/path", "destination": "/target/url", "permanent": true } ]

Learn about the CLI commands for redirects in the CLI guide.