Need help with dynamic routing specific city locations
Answered
Common Greenshank posted this in #help-forum
Common GreenshankOP
I need help with the following routing,
www.abc.com/abc-service-[location]
where location is the param in the page.tsx
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} />
}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
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
....
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-"@joulev 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 GreenshankOP
Can you please elaborate on this?
@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}` });
}