Function for constructing URL from Next.js dynamic route (with `[slug]`)

144 views Asked by At

This feels gross to me. Is there a better way to implement getUrlFromRouteWithSlug?

Does Next.js offer a function for it?

const TEACHER = "/teacher";
export const TEACHER_PROFILE = `${TEACHER}/profile`;
export const TEACHER_PROFILE_BY_TEACHEROF_ID = `${TEACHER_PROFILE}/[teacherOfId]`;

/**
 * E.g. Inputs 'exampleString[slug]', 'exampleString[secondSlug]', and 'exampleString' all return 'exampleString' if replaceValue is ''.
 */
function replaceTrailingSquareBracketsChunk(
  inputString: string,
  replaceValue: string
): string {
  const regex = /\[[^\]]*\]$/; // Matches text in square brackets at the end of the string. See test cases.
  return inputString.replace(regex, replaceValue);
}

function getUrlFromRouteWithSlug(route: string, slug: string): string {
  const href = `${BASE_URL}${replaceTrailingSquareBracketsChunk(route, "")}${slug}`;
  return href;
}

const url = getUrlFromRouteWithSlug(TEACHER_PROFILE_BY_TEACHEROF_ID, 'fkjhk435')

I couldn't find it at https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes or https://nextjs.org/learn-pages-router/basics/dynamic-routes/dynamic-routes-details

Elsewhere in our app, we rely on route definitions, such as:

if (router.route === TEACHER_PROFILE_BY_TEACHEROF_ID) {
  //...
}

So we need a clean way of building an URL via that route and its ingredients, which in this case is a single slug (teacherOfId).

And the TEACHER_PROFILE_BY_TEACHEROF_ID route needs to be treated as distinct from the TEACHER_PROFILE route.

0

There are 0 answers