Routing in Next.js
Outline
Next.js uses a file-based routing system that's intuitive and powerful. Here's how to implement it in an Optimizely SaaS CMS project.
Basic File-Based Routing
Routes are defined by the file structure in the app directory:
app/
├── page.tsx         # Home page (/)
├── about/
│   └── page.tsx     # About page (/about)
└── blog/
    └── page.tsx     # Blog page (/blog)Dynamic Routes for CMS Pages
For Optimizely CMS pages, use dynamic routes with square brackets [ ]:
app/
└── [locale]/
    ├── page.tsx           # Localized home page (/en, /sv, etc.)
    └── [slug]/
        └── page.tsx       # Dynamic CMS pages (/en/about, etc.)Example Implementation
1. Localized Home Page:
// app/[locale]/page.tsx
export default async function LocalizedHome({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  const { data } = await optimizely.GetStartPage({ locales: [locale] });
  return <h1>{data.StartPage.items[0].Title}</h1>;
}2. Dynamic CMS Pages:
// app/[locale]/[slug]/page.tsx
export default async function CmsPage({ params }: { params: Promise<{ locale: string; slug: string }> }) {
  const { locale, slug } = await params;
  const { data } = await optimizely.GetPageByURL({ locales: [locale], slug: `/${slug}` });
  if (!data?.CMSPage?.items?.[0]) return notFound();
  return <h1>{data.CMSPage.items[0].Title}</h1>;
}Route Groups
Next.js introduces the concept of Route Groups, which allow you to organize routes without affecting the URL structure.
For example:
app/
├── (marketing)/
│   ├── about/
│   │   └── page.tsx   # Still maps to /about
│   └── contact/
│       └── page.tsx   # Still maps to /contact
└── (shop)/
    ├── products/
    │   └── page.tsx   # Still maps to /products
    └── cart/
        └── page.tsx   # Still maps to /cartRoute groups are useful for:
- Organizing routes without affecting the URL structure
- Creating multiple root layouts
- Grouping routes for better code organization
Key Takeaways
-   File structure in app/defines routes
-   Use [brackets]for dynamic segments (e.g.,[locale],[slug])
- Params are now handled as Promises in page components
- Route groups organize code without changing URLs
