Redirects
The @frend-digital/next/redirects package contains a set of utilities for working with Next.js redirects.
Installation
pnpm add @frend-digital/nextUsage
import { matchRedirect } from "@frend-digital/next/redirects";
const result = matchRedirect("/test", [ { source: "/test", destination: "/test2", },]);
console.log(result); // { path: "/test2" }Using redirects in Next.js and Storyblok
-
Create a datasource in Storyblok with the following fields:
name: The source URL.value: The destination URL.
-
Fetch the datasource entries in your Next.js server-side code:
import { matchRedirect } from "@frend-digital/next/redirects";
async function fetchRedirect(path: string) { const { isEnabled } = await draftMode();
const entries: DatasourceEntry[] = []; let page = 0; let total = 0;
// Fetch all page redirects do { page++; const result = await storyblok.getDatasource({ preview: isEnabled, slug: "redirects", per_page: 1000, page: page, dimension: "", });
const data = Result.unwrap(result); total = data.total; entries.push(...data.data); } while (entries.length < total);
// Match the redirect against the URL return matchRedirect(path, entries);}- Use the
fetchRedirectfunction in your Next.js server-side code:
import { redirect, permanentRedirect } from "next/navigation"; // or "@/i18n/routing" if you're using i18n package
export async function Page(props: PageProps) { const { slug } = await getParams(props);
const path = addLeadingSlash(slug?.join("/") || "");
const foundRedirect = await fetchRedirect(path);
if (foundRedirect) { const navigate = foundRedirect.permanent ? permanentRedirect : redirect; navigate(foundRedirect.path); }
// Your other data fetching here.
// Render the page here return <div>Hello world!</div>;}API
matchRedirect
function matchRedirect( input: string | URL, entries: RedirectEntry[] | DatasourceEntry[]): { path: string; permanent?: boolean } | null;Matches a redirect from the given input URL to a destination URL.
Parameters
input: The input URL to match.entries: The redirect entries to match against.
Returns
A redirect object with the matched path and a boolean indicating if the redirect is permanent.
datasourceToRedirects
function datasourceToRedirects( datasourceEntries: { id: number; name: string; value: string; dimension_value?: string; }[]): RedirectEntry[];Converts a datasource entry array to a redirect entry array.
Parameters
datasourceEntries: The datasource entries to convert.
Returns
An array of redirect entries.