Next.js Discord

Discord Forum

Need help with dynamic routing specific city locations

Answered
Common Greenshank posted this in #help-forum
Open in Discord
Common GreenshankOP
I need help with the following routing,

www.abc.com/abc-service-[location]

where location is the param in the page.tsx
Answered by joulev
// app/[slug]/page.tsx
export default function Page({ params }) {
  const slug = params.slug;
  if (!slug.startsWith("abc-service-")) notFound();
  const location = slug.replace("abc-service-", "");
  return <LocationInfo location={location} />
}
View full answer

8 Replies

@Common Greenshank I need help with the following routing, www.abc.com/abc-service-[location] where location is the param in the page.tsx
you have multiple options you can do:
1. Save the slug inside your datasource and ask for it when someone visits the website.
2. Create the [location] as it's own dynamic element like /slug/location then you can directly ask for your location when somone visits the website.
Common GreenshankOP
Neither of this works for my case the only other i can think is to create 250 routes with different locations

so
www.abc.com/abc-service-sacramento
www.abc.com/abc-service-san-diego
www.abc.com/abc-service-los-angeles
....
@Common Greenshank I need help with the following routing, www.abc.com/abc-service-[location] where location is the param in the page.tsx
you can't have a template like abc-service-[location]. what you can do though is have a [locationTemplate] or something similar, then assert that locationTemplate starts with "abc-service-"
@Common Greenshank Can you please elaborate on this?
// app/[slug]/page.tsx
export default function Page({ params }) {
  const slug = params.slug;
  if (!slug.startsWith("abc-service-")) notFound();
  const location = slug.replace("abc-service-", "");
  return <LocationInfo location={location} />
}
Answer
Common GreenshankOP
I think this would work
Thank you
yep and in generateStaticParams (if you use it), just do something like
export async function generateStaticParams() {
  const locations = await getLocations();
  return locations.map(location => ({ slug: `abc-service-${location}` });
}