活动公告

系统通知
通知:由于主题天梯活动参与率不足,活动终止。后续将会替换为其他活动内容
07-12 12:44
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

深入探索 Next.js 个性化路由配置的艺术 从基础原理到高级实践 打造符合现代 Web 应用需求的定制化路由解决方案

SunJu_FaceMall

3万

主题

2689

科技点

3万

积分

执行版主

碾压王

积分
32881

塔罗立华奏

执行版主 发表于 2025-8-29 15:40:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

Next.js 作为 React 生态中最流行的服务端渲染框架之一,以其强大的路由系统而著称。从早期的页面路由到最新的 App Router,Next.js 的路由系统一直在不断演进,以满足现代 Web 应用日益复杂的需求。本文将深入探讨 Next.js 路由系统的个性化配置,从基础原理到高级实践,帮助开发者打造符合现代 Web 应用需求的定制化路由解决方案。

路由是 Web 应用的骨架,它不仅决定了应用的 URL 结构,还影响着用户体验、代码组织方式、性能优化等多个方面。通过掌握 Next.js 路由配置的艺术,开发者可以构建出更加灵活、高效且易于维护的 Web 应用。

Next.js 路由基础

文件系统路由原理

Next.js 采用了基于文件系统的路由机制,这是其核心特性之一。在这种机制下,文件和目录结构直接映射到应用的 URL 路径,使得路由管理变得直观且易于维护。

在 Next.js 13 之前,主要使用的是 Pages Router,其路由规则如下:

• pages/index.js→/
• pages/about.js→/about
• pages/blog/[slug].js→/blog/:slug

而随着 Next.js 13 的发布,引入了全新的 App Router,基于 React Server Components,提供了更强大的路由功能:

• app/page.js→/
• app/about/page.js→/about
• app/blog/[slug]/page.js→/blog/:slug

路由类型对比

Next.js 提供了两种路由系统:传统的 Pages Router 和现代的 App Router。

Pages Router的特点:

• 简单直观,易于上手
• 支持静态生成(SSG)和服务端渲染(SSR)
• 通过getStaticProps、getServerSideProps等函数获取数据

App Router的特点:

• 基于 React Server Components
• 支持嵌套路由、布局和模板
• 更细粒度的渲染控制(Streaming SSR)
• 服务器组件和客户端组件的分离

下面是一个基础的 App Router 结构示例:
  1. // app/layout.js - 根布局
  2. export default function RootLayout({ children }) {
  3.   return (
  4.     <html lang="en">
  5.       <body>{children}</body>
  6.     </html>
  7.   );
  8. }
  9. // app/page.js - 首页
  10. export default function HomePage() {
  11.   return <h1>Welcome to Next.js!</h1>;
  12. }
  13. // app/about/page.js - 关于页面
  14. export default function AboutPage() {
  15.   return <h1>About Us</h1>;
  16. }
复制代码

基础路由配置

静态路由

静态路由是最简单的路由形式,直接对应文件系统中的文件。

在 App Router 中:
  1. // app/products/page.js
  2. export default function ProductsPage() {
  3.   return (
  4.     <div>
  5.       <h1>Our Products</h1>
  6.       <p>Check out our amazing product lineup!</p>
  7.     </div>
  8.   );
  9. }
复制代码

这将创建一个/products路径,访问该路径将显示ProductsPage组件。

动态路由

动态路由允许我们创建包含参数的 URL,例如产品详情页、用户个人资料页等。

在 App Router 中,动态路由通过方括号[]定义:
  1. // app/products/[id]/page.js
  2. export default function ProductPage({ params }) {
  3.   return (
  4.     <div>
  5.       <h1>Product Details</h1>
  6.       <p>Viewing product with ID: {params.id}</p>
  7.     </div>
  8.   );
  9. }
复制代码

这将匹配/products/1、/products/abc等路径,并将id参数传递给组件。

嵌套路由

嵌套路由允许我们在 URL 结构中创建层次关系,同时保持组件的嵌套结构。

在 App Router 中,嵌套路由通过创建嵌套文件夹实现:
  1. // app/dashboard/layout.js
  2. export default function DashboardLayout({ children }) {
  3.   return (
  4.     <div>
  5.       <nav>Dashboard Navigation</nav>
  6.       {children}
  7.     </div>
  8.   );
  9. }
  10. // app/dashboard/page.js
  11. export default function DashboardHome() {
  12.   return <h1>Dashboard Home</h1>;
  13. }
  14. // app/dashboard/settings/page.js
  15. export default function DashboardSettings() {
  16.   return <h1>Dashboard Settings</h1>;
  17. }
复制代码

这样,/dashboard将显示DashboardHome组件,而/dashboard/settings将显示DashboardSettings组件,两者都会被包裹在DashboardLayout中。

路由组

路由组允许我们在不影响 URL 路径的情况下组织文件。通过将文件夹放在括号中,如(marketing),可以创建逻辑分组而不添加到 URL 中。
  1. // app/(marketing)/about/page.js
  2. export default function AboutPage() {
  3.   return <h1>About Us</h1>;
  4. }
  5. // app/(marketing)/contact/page.js
  6. export default function ContactPage() {
  7.   return <h1>Contact Us</h1>;
  8. }
复制代码

这些页面将分别对应/about和/contact路径,(marketing)文件夹名不会出现在 URL 中。

中间件与路由拦截

路由中间件基础

Next.js 中间件允许我们在请求完成之前运行代码,这对于实现路由守卫、重定向、身份验证等功能非常有用。

创建中间件文件middleware.js(或.ts)在项目根目录或与app目录同级:
  1. // middleware.js
  2. import { NextResponse } from 'next/server';
  3. import { nextAuth } from './lib/auth';
  4. export async function middleware(request) {
  5.   const { pathname } = request.nextUrl;
  6.   
  7.   // 检查用户是否已认证
  8.   const isAuthenticated = await nextAuth.isAuthenticated(request);
  9.   
  10.   // 如果访问受保护的路由但未认证,重定向到登录页
  11.   if (pathname.startsWith('/dashboard') && !isAuthenticated) {
  12.     return NextResponse.redirect(new URL('/login', request.url));
  13.   }
  14.   
  15.   return NextResponse.next();
  16. }
  17. // 配置中间件匹配的路径
  18. export const config = {
  19.   matcher: ['/dashboard/:path*', '/profile/:path*'],
  20. };
复制代码

高级中间件模式

中间件可以用于实现更复杂的路由拦截和修改逻辑:
  1. // middleware.js
  2. import { NextResponse } from 'next/server';
  3. export async function middleware(request) {
  4.   const { pathname, searchParams } = request.nextUrl;
  5.   const token = request.cookies.get('token')?.value;
  6.   
  7.   // A/B 测试路由分发
  8.   if (pathname === '/home') {
  9.     const variant = Math.random() > 0.5 ? 'a' : 'b';
  10.     return NextResponse.redirect(new URL(`/home-${variant}`, request.url));
  11.   }
  12.   
  13.   // 地理位置重定向
  14.   const country = request.geo?.country;
  15.   if (pathname === '/news' && country === 'CN') {
  16.     return NextResponse.redirect(new URL('/news/china', request.url));
  17.   }
  18.   
  19.   // API 速率限制
  20.   if (pathname.startsWith('/api/')) {
  21.     const clientIP = request.ip;
  22.     const rateLimitResult = await checkRateLimit(clientIP);
  23.    
  24.     if (!rateLimitResult.allowed) {
  25.       return new NextResponse('Too many requests', { status: 429 });
  26.     }
  27.   }
  28.   
  29.   // 添加自定义响应头
  30.   const response = NextResponse.next();
  31.   response.headers.set('X-Custom-Header', 'Custom Value');
  32.   
  33.   return response;
  34. }
  35. // 辅助函数:检查速率限制
  36. async function checkRateLimit(ip) {
  37.   // 实现速率限制逻辑
  38.   return { allowed: true };
  39. }
  40. export const config = {
  41.   matcher: [
  42.     '/((?!_next/static|_next/image|favicon.ico).*)',
  43.   ],
  44. };
复制代码

基于角色的访问控制

中间件还可以用于实现基于角色的访问控制(RBAC):
  1. // middleware.js
  2. import { NextResponse } from 'next/server';
  3. import { verifyToken } from './lib/auth';
  4. export async function middleware(request) {
  5.   const { pathname } = request.nextUrl;
  6.   const token = request.cookies.get('auth_token')?.value;
  7.   
  8.   // 不需要认证的路径
  9.   const publicPaths = ['/login', '/register', '/'];
  10.   if (publicPaths.includes(pathname)) {
  11.     return NextResponse.next();
  12.   }
  13.   
  14.   // 验证令牌
  15.   if (!token) {
  16.     return NextResponse.redirect(new URL('/login', request.url));
  17.   }
  18.   
  19.   const user = await verifyToken(token);
  20.   
  21.   if (!user) {
  22.     return NextResponse.redirect(new URL('/login', request.url));
  23.   }
  24.   
  25.   // 基于角色的路由保护
  26.   const roleBasedPaths = {
  27.     '/admin': ['admin'],
  28.     '/dashboard': ['user', 'admin'],
  29.     '/settings': ['user', 'admin'],
  30.   };
  31.   
  32.   for (const [path, allowedRoles] of Object.entries(roleBasedPaths)) {
  33.     if (pathname.startsWith(path) && !allowedRoles.includes(user.role)) {
  34.       return NextResponse.redirect(new URL('/unauthorized', request.url));
  35.     }
  36.   }
  37.   
  38.   // 将用户信息添加到请求头中,以便在路由中使用
  39.   const requestHeaders = new Headers(request.headers);
  40.   requestHeaders.set('x-user-id', user.id);
  41.   requestHeaders.set('x-user-role', user.role);
  42.   
  43.   return NextResponse.next({
  44.     request: {
  45.       headers: requestHeaders,
  46.     },
  47.   });
  48. }
  49. export const config = {
  50.   matcher: [
  51.     '/((?!_next/static|_next/image|favicon.ico|api/auth).*)',
  52.   ],
  53. };
复制代码

高级路由模式

并行路由

并行路由允许在同一布局中同时渲染多个独立的页面,这对于创建复杂的应用界面(如仪表板)非常有用。

在 App Router 中,并行路由通过命名插槽实现:
  1. // app/dashboard/@analytics/page.js
  2. export default function Analytics() {
  3.   return <div>Analytics Panel</div>;
  4. }
  5. // app/dashboard/@team/page.js
  6. export default function Team() {
  7.   return <div>Team Panel</div>;
  8. }
  9. // app/dashboard/layout.js
  10. export default function DashboardLayout({
  11.   children,
  12.   analytics,
  13.   team,
  14. }) {
  15.   return (
  16.     <div className="dashboard">
  17.       <aside>{children}</aside>
  18.       <div className="main-content">
  19.         <section className="analytics">{analytics}</section>
  20.         <section className="team">{team}</section>
  21.       </div>
  22.     </div>
  23.   );
  24. }
复制代码

这样,当访问/dashboard时,将同时渲染默认的children、Analytics和Team组件。我们还可以通过路由如/dashboard/@analytics单独访问某个插槽。

拦截路由

拦截路由允许我们在当前页面的上下文中显示路由内容,而不离开当前页面。这对于模态框、抽屉等 UI 模式非常有用。
  1. // app/photos/[id]/page.js
  2. export default function PhotoPage({ params }) {
  3.   return <div>Viewing photo {params.id}</div>;
  4. }
  5. // app/@modal/(..)photos/[id]/page.js
  6. export default function PhotoModal({ params }) {
  7.   return (
  8.     <div className="modal">
  9.       <h2>Photo Modal</h2>
  10.       <p>Viewing photo {params.id} in a modal</p>
  11.     </div>
  12.   );
  13. }
  14. // app/layout.js
  15. import { Suspense } from 'react';
  16. export default function RootLayout({ children, modal }) {
  17.   return (
  18.     <html>
  19.       <body>
  20.         {children}
  21.         <Suspense fallback={null}>{modal}</Suspense>
  22.       </body>
  23.     </html>
  24.   );
  25. }
复制代码

通过这种方式,当用户点击照片链接时,可以在模态框中显示照片详情,而不离开当前页面。

条件路由

条件路由允许我们根据特定条件(如用户设备、地理位置、时间等)提供不同的路由体验。
  1. // app/page.js
  2. import { redirect } from 'next/navigation';
  3. import { isMobileDevice } from '@/lib/device';
  4. export default async function Home() {
  5.   const isMobile = await isMobileDevice();
  6.   
  7.   if (isMobile) {
  8.     redirect('/mobile-home');
  9.   }
  10.   
  11.   return <div>Desktop Home Page</div>;
  12. }
  13. // app/mobile-home/page.js
  14. export default function MobileHome() {
  15.   return <div>Mobile Home Page</div>;
  16. }
复制代码

动态路由与数据获取

动态路由通常需要根据路由参数获取数据。在 App Router 中,我们可以使用 React Server Components 直接在组件中获取数据:
  1. // app/blog/[slug]/page.js
  2. async function getBlogPost(slug) {
  3.   const res = await fetch(`https://api.example.com/blog/${slug}`, {
  4.     cache: 'force-cache', // 默认行为,静态生成
  5.     // 或者使用 { cache: 'no-store' } 进行动态渲染
  6.   });
  7.   
  8.   if (!res.ok) {
  9.     throw new Error('Failed to fetch blog post');
  10.   }
  11.   
  12.   return res.json();
  13. }
  14. export default async function BlogPostPage({ params }) {
  15.   const post = await getBlogPost(params.slug);
  16.   
  17.   return (
  18.     <article>
  19.       <h1>{post.title}</h1>
  20.       <div dangerouslySetInnerHTML={{ __html: post.content }} />
  21.     </article>
  22.   );
  23. }
复制代码

对于更复杂的数据获取场景,我们可以使用generateStaticParams函数预构建静态页面:
  1. // app/blog/[slug]/page.js
  2. async function getBlogSlugs() {
  3.   const res = await fetch('https://api.example.com/blog/slugs');
  4.   const slugs = await res.json();
  5.   return slugs;
  6. }
  7. export async function generateStaticParams() {
  8.   const slugs = await getBlogSlugs();
  9.   return slugs.map((slug) => ({ slug }));
  10. }
  11. // ...其余代码与上面相同
复制代码

路由优化与性能

代码分割与懒加载

Next.js 默认会对每个页面进行代码分割,但我们还可以进一步优化,通过动态导入实现组件级别的懒加载:
  1. // app/components/heavy-component.js
  2. export default function HeavyComponent() {
  3.   return <div>This is a heavy component with lots of dependencies</div>;
  4. }
  5. // app/page.js
  6. import dynamic from 'next/dynamic';
  7. // 动态导入 HeavyComponent,不进行 SSR
  8. const HeavyComponent = dynamic(
  9.   () => import('../components/heavy-component'),
  10.   { ssr: false }
  11. );
  12. // 带有加载状态的动态导入
  13. const HeavyComponentWithLoading = dynamic(
  14.   () => import('../components/heavy-component'),
  15.   {
  16.     loading: () => <p>Loading...</p>,
  17.     ssr: false
  18.   }
  19. );
  20. export default function HomePage() {
  21.   return (
  22.     <div>
  23.       <h1>Welcome to the Home Page</h1>
  24.       <HeavyComponent />
  25.       <HeavyComponentWithLoading />
  26.     </div>
  27.   );
  28. }
复制代码

路由预加载

Next.js 提供了<Link>组件的prefetch属性,可以在后台预加载页面资源,提高导航速度:
  1. // app/components/navigation.js
  2. import Link from 'next/link';
  3. export default function Navigation() {
  4.   return (
  5.     <nav>
  6.       <Link href="/" prefetch={true}>Home</Link>
  7.       <Link href="/about" prefetch={true}>About</Link>
  8.       <Link href="/contact" prefetch={true}>Contact</Link>
  9.     </nav>
  10.   );
  11. }
复制代码

对于更精细的控制,我们可以使用router.prefetch方法:
  1. // app/components/product-card.js
  2. 'use client';
  3. import { useRouter } from 'next/navigation';
  4. import { useEffect } from 'react';
  5. export default function ProductCard({ product }) {
  6.   const router = useRouter();
  7.   
  8.   useEffect(() => {
  9.     // 当鼠标悬停在卡片上时预加载产品详情页
  10.     router.prefetch(`/products/${product.id}`);
  11.   }, [product.id, router]);
  12.   
  13.   return (
  14.     <div
  15.       onClick={() => router.push(`/products/${product.id}`)}
  16.       style={{ cursor: 'pointer' }}
  17.     >
  18.       <h3>{product.name}</h3>
  19.       <p>{product.description}</p>
  20.     </div>
  21.   );
  22. }
复制代码

缓存策略优化

在 App Router 中,我们可以通过fetchAPI 的cache选项精细控制数据缓存策略:
  1. // app/products/page.js
  2. async function getProducts() {
  3.   // 使用默认缓存(静态生成)
  4.   const res = await fetch('https://api.example.com/products');
  5.   return res.json();
  6. }
  7. async function getRealTimeData() {
  8.   // 不缓存,每次请求都重新获取
  9.   const res = await fetch('https://api.example.com/real-time-data', {
  10.     cache: 'no-store',
  11.   });
  12.   return res.json();
  13. }
  14. async function getRevalidatedData() {
  15.   // 缓存数据,但最多 60 秒后重新验证
  16.   const res = await fetch('https://api.example.com/revalidated-data', {
  17.     next: { revalidate: 60 },
  18.   });
  19.   return res.json();
  20. }
  21. export default async function ProductsPage() {
  22.   const products = await getProducts();
  23.   const realTimeData = await getRealTimeData();
  24.   const revalidatedData = await getRevalidatedData();
  25.   
  26.   return (
  27.     <div>
  28.       <h1>Products</h1>
  29.       {/* 渲染产品列表 */}
  30.     </div>
  31.   );
  32. }
复制代码

路由级性能优化

我们可以通过路由配置实现更细粒度的性能优化:
  1. // app/shop/[category]/[product]/page.js
  2. import { unstable_cache } from 'next/cache';
  3. async function getProduct(category, product) {
  4.   // 使用不稳定缓存 API 缓存数据获取函数
  5.   const getProductData = unstable_cache(
  6.     async () => {
  7.       const res = await fetch(`https://api.example.com/shop/${category}/${product}`);
  8.       return res.json();
  9.     },
  10.     [`product-${category}-${product}`],
  11.     {
  12.       revalidate: 3600, // 1 小时后重新验证
  13.       tags: [`product-${product}`], // 用于按需重新验证
  14.     }
  15.   );
  16.   
  17.   return getProductData();
  18. }
  19. export default async function ProductPage({ params }) {
  20.   const product = await getProduct(params.category, params.product);
  21.   
  22.   return (
  23.     <div>
  24.       <h1>{product.name}</h1>
  25.       <p>{product.description}</p>
  26.       <p>Price: ${product.price}</p>
  27.     </div>
  28.   );
  29. }
  30. // 按需重新验证的 API 路由
  31. // app/api/revalidate/route.js
  32. import { revalidateTag } from 'next/cache';
  33. export async function POST(request) {
  34.   const { tag } = await request.json();
  35.   
  36.   revalidateTag(tag);
  37.   
  38.   return Response.json({ revalidated: true, now: Date.now() });
  39. }
复制代码

自定义路由配置

next.config.js 路由配置

通过next.config.js文件,我们可以实现更高级的路由配置:
  1. // next.config.js
  2. module.exports = {
  3.   // 自定义页面扩展名
  4.   pageExtensions: ['jsx', 'js', 'tsx', 'ts'],
  5.   
  6.   // 路径别名
  7.   webpack: (config) => {
  8.     config.resolve.alias = {
  9.       ...config.resolve.alias,
  10.       '@components': './components',
  11.       '@lib': './lib',
  12.     };
  13.     return config;
  14.   },
  15.   
  16.   // 重写和重定向
  17.   async rewrites() {
  18.     return [
  19.       {
  20.         source: '/dashboard',
  21.         destination: '/dashboard/overview',
  22.       },
  23.       {
  24.         source: '/blog/:slug',
  25.         destination: '/articles/:slug',
  26.       },
  27.     ];
  28.   },
  29.   
  30.   async redirects() {
  31.     return [
  32.       {
  33.         source: '/old-home',
  34.         destination: '/',
  35.         permanent: true,
  36.       },
  37.       {
  38.         source: '/admin/:path*',
  39.         destination: '/dashboard/:path*',
  40.         permanent: false,
  41.       },
  42.     ];
  43.   },
  44.   
  45.   // 头部配置
  46.   async headers() {
  47.     return [
  48.       {
  49.         source: '/(.*)',
  50.         headers: [
  51.           {
  52.             key: 'X-Frame-Options',
  53.             value: 'DENY',
  54.           },
  55.           {
  56.             key: 'X-Content-Type-Options',
  57.             value: 'nosniff',
  58.           },
  59.         ],
  60.       },
  61.     ];
  62.   },
  63. };
复制代码

自定义路由处理

我们可以创建自定义路由处理程序来处理特定的路由模式:
  1. // app/api/route.js
  2. import { NextResponse } from 'next/server';
  3. export async function GET(request) {
  4.   const { searchParams } = new URL(request.url);
  5.   const id = searchParams.get('id');
  6.   
  7.   const data = await fetchData(id);
  8.   
  9.   return NextResponse.json(data);
  10. }
  11. export async function POST(request) {
  12.   const body = await request.json();
  13.   
  14.   const result = await createData(body);
  15.   
  16.   return NextResponse.json(result, { status: 201 });
  17. }
复制代码

国际化路由配置

Next.js 提供了内置的国际化(i18n)支持,我们可以配置基于子路径或域名的多语言路由:
  1. // next.config.js
  2. module.exports = {
  3.   i18n: {
  4.     locales: ['en', 'fr', 'de'],
  5.     defaultLocale: 'en',
  6.     domains: [
  7.       {
  8.         domain: 'example.com',
  9.         defaultLocale: 'en',
  10.       },
  11.       {
  12.         domain: 'example.fr',
  13.         defaultLocale: 'fr',
  14.       },
  15.       {
  16.         domain: 'example.de',
  17.         defaultLocale: 'de',
  18.       },
  19.     ],
  20.   },
  21. };
复制代码

然后,我们可以创建基于语言的路由结构:
  1. // app/[locale]/layout.js
  2. import { NextIntlClientProvider } from 'next-intl';
  3. import { getMessages } from 'next-intl/server';
  4. import { notFound } from 'next/navigation';
  5. const locales = ['en', 'fr', 'de'];
  6. export default async function LocaleLayout({
  7.   children,
  8.   params: { locale }
  9. }) {
  10.   // 验证是否提供了有效的 locale
  11.   if (!locales.includes(locale as any)) notFound();
  12.   
  13.   // 提供所有消息,以便在客户端组件中使用
  14.   const messages = await getMessages();
  15.   
  16.   return (
  17.     <NextIntlClientProvider messages={messages}>
  18.       {children}
  19.     </NextIntlClientProvider>
  20.   );
  21. }
  22. // app/[locale]/page.js
  23. export default function HomePage() {
  24.   return (
  25.     <div>
  26.       <h1>Welcome to the Home Page</h1>
  27.       {/* 本地化内容 */}
  28.     </div>
  29.   );
  30. }
复制代码

动态路由生成

对于需要动态生成大量路由的场景,我们可以使用generateStaticParams结合外部数据源:
  1. // app/docs/[...slug]/page.js
  2. async function getAllDocPaths() {
  3.   const res = await fetch('https://api.example.com/docs/paths');
  4.   const paths = await res.json();
  5.   return paths;
  6. }
  7. export async function generateStaticParams() {
  8.   const paths = await getAllDocPaths();
  9.   
  10.   return paths.map((path) => ({
  11.     slug: path.split('/'),
  12.   }));
  13. }
  14. export default async function DocPage({ params }) {
  15.   const { slug } = params;
  16.   const path = slug.join('/');
  17.   
  18.   const res = await fetch(`https://api.example.com/docs/${path}`);
  19.   const doc = await res.json();
  20.   
  21.   return (
  22.     <div>
  23.       <h1>{doc.title}</h1>
  24.       <div dangerouslySetInnerHTML={{ __html: doc.content }} />
  25.     </div>
  26.   );
  27. }
复制代码

实战案例

构建多租户 SaaS 应用路由

让我们构建一个具有多租户支持的 SaaS 应用路由系统:
  1. // middleware.js
  2. import { NextResponse } from 'next/server';
  3. export async function middleware(request) {
  4.   const { pathname, host } = request.nextUrl;
  5.   
  6.   // 从主机名提取租户信息
  7.   const subdomain = host.split('.')[0];
  8.   
  9.   // 跳过静态资源和 API 路由
  10.   if (
  11.     pathname.startsWith('/_next') ||
  12.     pathname.startsWith('/api') ||
  13.     pathname.startsWith('/static')
  14.   ) {
  15.     return NextResponse.next();
  16.   }
  17.   
  18.   // 租户特定的重定向
  19.   if (pathname === '/') {
  20.     return NextResponse.redirect(new URL(`/dashboard`, request.url));
  21.   }
  22.   
  23.   // 添加租户信息到请求头
  24.   const requestHeaders = new Headers(request.headers);
  25.   requestHeaders.set('x-tenant', subdomain);
  26.   
  27.   return NextResponse.next({
  28.     request: {
  29.       headers: requestHeaders,
  30.     },
  31.   });
  32. }
  33. export const config = {
  34.   matcher: [
  35.     '/((?!_next/static|_next/image|favicon.ico|api/auth).*)',
  36.   ],
  37. };
复制代码
  1. // app/layout.js
  2. import './globals.css';
  3. export const metadata = {
  4.   title: 'Multi-tenant SaaS Application',
  5.   description: 'A demo of multi-tenant routing in Next.js',
  6. };
  7. export default function RootLayout({ children }) {
  8.   return (
  9.     <html lang="en">
  10.       <body>{children}</body>
  11.     </html>
  12.   );
  13. }
复制代码
  1. // app/dashboard/layout.js
  2. import { Suspense } from 'react';
  3. import TenantProvider from '@/components/TenantProvider';
  4. export default function DashboardLayout({
  5.   children,
  6.   analytics,
  7.   settings,
  8. }) {
  9.   return (
  10.     <TenantProvider>
  11.       <div className="dashboard">
  12.         <aside>
  13.           <nav>
  14.             {/* 租户特定的导航 */}
  15.           </nav>
  16.         </aside>
  17.         <main>
  18.           <Suspense fallback={<div>Loading...</div>}>
  19.             {children}
  20.           </Suspense>
  21.         </main>
  22.         <div className="panels">
  23.           <Suspense fallback={<div>Loading analytics...</div>}>
  24.             {analytics}
  25.           </Suspense>
  26.           <Suspense fallback={<div>Loading settings...</div>}>
  27.             {settings}
  28.           </Suspense>
  29.         </div>
  30.       </div>
  31.     </TenantProvider>
  32.   );
  33. }
复制代码
  1. // app/components/TenantProvider.js
  2. 'use client';
  3. import { createContext, useContext, useEffect, useState } from 'react';
  4. const TenantContext = createContext();
  5. export function TenantProvider({ children }) {
  6.   const [tenant, setTenant] = useState(null);
  7.   const [loading, setLoading] = useState(true);
  8.   
  9.   useEffect(() => {
  10.     async function loadTenant() {
  11.       try {
  12.         // 从 API 获取租户信息
  13.         const res = await fetch('/api/tenant');
  14.         const data = await res.json();
  15.         setTenant(data);
  16.       } catch (error) {
  17.         console.error('Failed to load tenant:', error);
  18.       } finally {
  19.         setLoading(false);
  20.       }
  21.     }
  22.    
  23.     loadTenant();
  24.   }, []);
  25.   
  26.   if (loading) {
  27.     return <div>Loading tenant information...</div>;
  28.   }
  29.   
  30.   return (
  31.     <TenantContext.Provider value={{ tenant }}>
  32.       {children}
  33.     </TenantContext.Provider>
  34.   );
  35. }
  36. export function useTenant() {
  37.   return useContext(TenantContext);
  38. }
复制代码
  1. // app/api/tenant/route.js
  2. import { headers } from 'next/headers';
  3. export async function GET() {
  4.   const headersList = headers();
  5.   const tenantSubdomain = headersList.get('x-tenant');
  6.   
  7.   // 根据子域名获取租户信息
  8.   // 这里可以是数据库查询或其他数据源
  9.   const tenant = await getTenantBySubdomain(tenantSubdomain);
  10.   
  11.   if (!tenant) {
  12.     return Response.json({ error: 'Tenant not found' }, { status: 404 });
  13.   }
  14.   
  15.   return Response.json(tenant);
  16. }
  17. async function getTenantBySubdomain(subdomain) {
  18.   // 模拟数据库查询
  19.   const tenants = {
  20.     'client1': { id: 1, name: 'Client 1', theme: 'light' },
  21.     'client2': { id: 2, name: 'Client 2', theme: 'dark' },
  22.   };
  23.   
  24.   return tenants[subdomain] || null;
  25. }
复制代码

构建电子商务网站路由

让我们构建一个具有复杂路由需求的电子商务网站:
  1. // middleware.js
  2. import { NextResponse } from 'next/server';
  3. export async function middleware(request) {
  4.   const { pathname, searchParams } = request.nextUrl;
  5.   
  6.   // 从查询参数获取优惠码
  7.   const couponCode = searchParams.get('coupon');
  8.   
  9.   if (couponCode) {
  10.     // 验证优惠码
  11.     const isValid = await validateCoupon(couponCode);
  12.    
  13.     if (isValid) {
  14.       // 将优惠码存储在 cookie 中
  15.       const response = NextResponse.next();
  16.       response.cookies.set('coupon_code', couponCode, {
  17.         maxAge: 60 * 60 * 24, // 1 天
  18.         httpOnly: true,
  19.       });
  20.       return response;
  21.     }
  22.   }
  23.   
  24.   // 产品类别重定向
  25.   if (pathname.startsWith('/products/')) {
  26.     const category = pathname.split('/')[2];
  27.    
  28.     // 检查类别是否存在
  29.     const categoryExists = await checkCategoryExists(category);
  30.    
  31.     if (!categoryExists) {
  32.       return NextResponse.redirect(new URL('/products', request.url));
  33.     }
  34.   }
  35.   
  36.   return NextResponse.next();
  37. }
  38. async function validateCoupon(code) {
  39.   // 实现优惠码验证逻辑
  40.   return true;
  41. }
  42. async function checkCategoryExists(category) {
  43.   // 实现类别检查逻辑
  44.   return true;
  45. }
  46. export const config = {
  47.   matcher: [
  48.     '/((?!_next/static|_next/image|favicon.ico).*)',
  49.   ],
  50. };
复制代码
  1. // app/products/page.js
  2. import ProductGrid from '@/components/ProductGrid';
  3. import Filters from '@/components/Filters';
  4. import SortOptions from '@/components/SortOptions';
  5. async function getProducts({ searchParams }) {
  6.   const { category, sort, minPrice, maxPrice } = searchParams;
  7.   
  8.   const params = new URLSearchParams();
  9.   if (category) params.append('category', category);
  10.   if (sort) params.append('sort', sort);
  11.   if (minPrice) params.append('minPrice', minPrice);
  12.   if (maxPrice) params.append('maxPrice', maxPrice);
  13.   
  14.   const res = await fetch(`https://api.example.com/products?${params}`);
  15.   return res.json();
  16. }
  17. async function getCategories() {
  18.   const res = await fetch('https://api.example.com/categories');
  19.   return res.json();
  20. }
  21. export default async function ProductsPage({ searchParams }) {
  22.   const products = await getProducts({ searchParams });
  23.   const categories = await getCategories();
  24.   
  25.   return (
  26.     <div className="products-page">
  27.       <h1>Our Products</h1>
  28.       
  29.       <div className="filters-sidebar">
  30.         <Filters categories={categories} />
  31.       </div>
  32.       
  33.       <div className="products-content">
  34.         <SortOptions />
  35.         <ProductGrid products={products} />
  36.       </div>
  37.     </div>
  38.   );
  39. }
复制代码
  1. // app/products/[category]/page.js
  2. import ProductGrid from '@/components/ProductGrid';
  3. import Filters from '@/components/Filters';
  4. import SortOptions from '@/components/SortOptions';
  5. async function getProductsByCategory(category, { searchParams }) {
  6.   const { sort, minPrice, maxPrice } = searchParams;
  7.   
  8.   const params = new URLSearchParams();
  9.   params.append('category', category);
  10.   if (sort) params.append('sort', sort);
  11.   if (minPrice) params.append('minPrice', minPrice);
  12.   if (maxPrice) params.append('maxPrice', maxPrice);
  13.   
  14.   const res = await fetch(`https://api.example.com/products?${params}`);
  15.   return res.json();
  16. }
  17. async function getCategoryDetails(category) {
  18.   const res = await fetch(`https://api.example.com/categories/${category}`);
  19.   return res.json();
  20. }
  21. export async function generateStaticParams() {
  22.   const res = await fetch('https://api.example.com/categories');
  23.   const categories = await res.json();
  24.   
  25.   return categories.map((category) => ({
  26.     category: category.slug,
  27.   }));
  28. }
  29. export default async function CategoryPage({ params, searchParams }) {
  30.   const { category } = params;
  31.   const products = await getProductsByCategory(category, { searchParams });
  32.   const categoryDetails = await getCategoryDetails(category);
  33.   
  34.   return (
  35.     <div className="category-page">
  36.       <h1>{categoryDetails.name}</h1>
  37.       <p>{categoryDetails.description}</p>
  38.       
  39.       <div className="filters-sidebar">
  40.         <Filters />
  41.       </div>
  42.       
  43.       <div className="products-content">
  44.         <SortOptions />
  45.         <ProductGrid products={products} />
  46.       </div>
  47.     </div>
  48.   );
  49. }
复制代码
  1. // app/products/[category]/[slug]/page.js
  2. import { notFound } from 'next/navigation';
  3. import ProductGallery from '@/components/ProductGallery';
  4. import ProductInfo from '@/components/ProductInfo';
  5. import RelatedProducts from '@/components/RelatedProducts';
  6. import AddToCartButton from '@/components/AddToCartButton';
  7. async function getProduct(category, slug) {
  8.   const res = await fetch(`https://api.example.com/products/${slug}`, {
  9.     next: { revalidate: 3600 }, // 1 小时后重新验证
  10.   });
  11.   
  12.   if (!res.ok) {
  13.     return null;
  14.   }
  15.   
  16.   return res.json();
  17. }
  18. async function getRelatedProducts(productId) {
  19.   const res = await fetch(`https://api.example.com/products/${productId}/related`);
  20.   return res.json();
  21. }
  22. export async function generateStaticParams() {
  23.   const res = await fetch('https://api.example.com/products');
  24.   const products = await res.json();
  25.   
  26.   return products.map((product) => ({
  27.     category: product.category.slug,
  28.     slug: product.slug,
  29.   }));
  30. }
  31. export default async function ProductPage({ params }) {
  32.   const { category, slug } = params;
  33.   const product = await getProduct(category, slug);
  34.   
  35.   if (!product) {
  36.     notFound();
  37.   }
  38.   
  39.   const relatedProducts = await getRelatedProducts(product.id);
  40.   
  41.   return (
  42.     <div className="product-page">
  43.       <div className="product-main">
  44.         <ProductGallery images={product.images} />
  45.         <div className="product-details">
  46.           <ProductInfo product={product} />
  47.           <AddToCartButton product={product} />
  48.         </div>
  49.       </div>
  50.       
  51.       <div className="related-products">
  52.         <h2>You might also like</h2>
  53.         <RelatedProducts products={relatedProducts} />
  54.       </div>
  55.     </div>
  56.   );
  57. }
复制代码

最佳实践与注意事项

路由组织最佳实践

1. 保持路由结构简单直观:遵循 Next.js 的约定优于配置原则,尽量使用文件系统路由。
2. 合理使用路由组:使用路由组(folder-name)组织相关页面,而不影响 URL 结构。
3. 避免过度嵌套:过深的路由嵌套会使应用变得复杂,尽量保持路由层次扁平。
4. 使用布局减少代码重复:将共享的 UI 元素(如导航、页脚)放在布局组件中。

保持路由结构简单直观:遵循 Next.js 的约定优于配置原则,尽量使用文件系统路由。

合理使用路由组:使用路由组(folder-name)组织相关页面,而不影响 URL 结构。

避免过度嵌套:过深的路由嵌套会使应用变得复杂,尽量保持路由层次扁平。

使用布局减少代码重复:将共享的 UI 元素(如导航、页脚)放在布局组件中。
  1. // 良好的路由组织示例
  2. app/
  3. ├── (auth)/
  4. │   ├── login/
  5. │   │   └── page.js
  6. │   └── register/
  7. │       └── page.js
  8. ├── (dashboard)/
  9. │   ├── layout.js
  10. │   ├── page.js
  11. │   ├── analytics/
  12. │   │   └── page.js
  13. │   └── settings/
  14. │       └── page.js
  15. ├── (marketing)/
  16. │   ├── about/
  17. │   │   └── page.js
  18. │   └── contact/
  19. │       └── page.js
  20. ├── api/
  21. │   └── auth/
  22. │       └── route.js
  23. ├── layout.js
  24. └── page.js
复制代码

性能优化最佳实践

1. 使用静态生成:对于不经常变化的内容,使用静态生成(SSG)提高性能。
2. 实现增量静态再生成:对于需要定期更新的内容,使用 ISR。
3. 懒加载非关键组件:使用next/dynamic懒加载大型组件或非首屏组件。
4. 优化数据获取:在服务器组件中获取数据,减少客户端 JavaScript 包大小。
5. 使用预加载:对于用户可能访问的页面,使用<Link prefetch>或router.prefetch()预加载。

使用静态生成:对于不经常变化的内容,使用静态生成(SSG)提高性能。

实现增量静态再生成:对于需要定期更新的内容,使用 ISR。

懒加载非关键组件:使用next/dynamic懒加载大型组件或非首屏组件。

优化数据获取:在服务器组件中获取数据,减少客户端 JavaScript 包大小。

使用预加载:对于用户可能访问的页面,使用<Link prefetch>或router.prefetch()预加载。
  1. // 性能优化示例
  2. import dynamic from 'next/dynamic';
  3. import Link from 'next/link';
  4. // 懒加载大型组件
  5. const HeavyChart = dynamic(
  6.   () => import('../components/HeavyChart'),
  7.   {
  8.     loading: () => <div>Loading chart...</div>,
  9.     ssr: false
  10.   }
  11. );
  12. // 预加载页面
  13. function Navigation() {
  14.   return (
  15.     <nav>
  16.       <Link href="/dashboard" prefetch={true}>Dashboard</Link>
  17.       <Link href="/analytics" prefetch={true}>Analytics</Link>
  18.     </nav>
  19.   );
  20. }
  21. // 服务器组件中获取数据
  22. async function BlogPage() {
  23.   const posts = await getBlogPosts(); // 在服务器上获取数据
  24.   
  25.   return (
  26.     <div>
  27.       <h1>Blog Posts</h1>
  28.       {posts.map(post => (
  29.         <div key={post.id}>
  30.           <h2>{post.title}</h2>
  31.           <p>{post.excerpt}</p>
  32.         </div>
  33.       ))}
  34.     </div>
  35.   );
  36. }
复制代码

安全性最佳实践

1. 验证路由参数:始终验证动态路由参数,防止恶意输入。
2. 实现适当的认证和授权:使用中间件保护敏感路由。
3. 避免在 URL 中暴露敏感信息:不要将敏感数据(如 ID、令牌)放在 URL 中。
4. 使用 HTTPS:确保所有路由都通过 HTTPS 提供服务。

验证路由参数:始终验证动态路由参数,防止恶意输入。

实现适当的认证和授权:使用中间件保护敏感路由。

避免在 URL 中暴露敏感信息:不要将敏感数据(如 ID、令牌)放在 URL 中。

使用 HTTPS:确保所有路由都通过 HTTPS 提供服务。
  1. // 安全路由参数验证示例
  2. export default function UserProfilePage({ params }) {
  3.   const { userId } = params;
  4.   
  5.   // 验证 userId 是否为有效的 UUID
  6.   if (!isValidUUID(userId)) {
  7.     notFound();
  8.   }
  9.   
  10.   // 获取用户数据
  11.   const user = getUserById(userId);
  12.   
  13.   if (!user) {
  14.     notFound();
  15.   }
  16.   
  17.   // 检查当前用户是否有权查看此用户资料
  18.   if (!canViewUserProfile(user)) {
  19.     redirect('/unauthorized');
  20.   }
  21.   
  22.   return <UserProfile user={user} />;
  23. }
  24. // 中间件认证示例
  25. export async function middleware(request) {
  26.   const token = request.cookies.get('auth_token')?.value;
  27.   
  28.   // 检查令牌是否存在
  29.   if (!token) {
  30.     return NextResponse.redirect(new URL('/login', request.url));
  31.   }
  32.   
  33.   // 验证令牌
  34.   const user = await verifyToken(token);
  35.   
  36.   if (!user) {
  37.     // 删除无效令牌
  38.     const response = NextResponse.redirect(new URL('/login', request.url));
  39.     response.cookies.delete('auth_token');
  40.     return response;
  41.   }
  42.   
  43.   // 将用户信息添加到请求头
  44.   const requestHeaders = new Headers(request.headers);
  45.   requestHeaders.set('x-user-id', user.id);
  46.   requestHeaders.set('x-user-role', user.role);
  47.   
  48.   return NextResponse.next({
  49.     request: {
  50.       headers: requestHeaders,
  51.     },
  52.   });
  53. }
复制代码

可访问性最佳实践

1. 使用语义 HTML:确保路由结构使用适当的 HTML5 语义元素。
2. 提供导航辅助功能:包括跳过导航链接、面包屑导航等。
3. 管理焦点:页面导航时适当管理键盘焦点。
4. 提供有意义的页面标题:每个页面应有描述性的标题。

使用语义 HTML:确保路由结构使用适当的 HTML5 语义元素。

提供导航辅助功能:包括跳过导航链接、面包屑导航等。

管理焦点:页面导航时适当管理键盘焦点。

提供有意义的页面标题:每个页面应有描述性的标题。
  1. // 可访问性路由示例
  2. // app/layout.js
  3. export default function RootLayout({ children }) {
  4.   return (
  5.     <html lang="en">
  6.       <body>
  7.         <a href="#main-content" className="skip-link">
  8.           Skip to main content
  9.         </a>
  10.         <nav aria-label="Main navigation">
  11.           {/* 导航内容 */}
  12.         </nav>
  13.         <main id="main-content" tabIndex={-1}>
  14.           {children}
  15.         </main>
  16.         <footer aria-label="Site footer">
  17.           {/* 页脚内容 */}
  18.         </footer>
  19.       </body>
  20.     </html>
  21.   );
  22. }
  23. // app/products/[slug]/page.js
  24. export async function generateMetadata({ params }) {
  25.   const product = await getProduct(params.slug);
  26.   
  27.   return {
  28.     title: `${product.name} - Our Store`,
  29.     description: product.description,
  30.   };
  31. }
  32. export default function ProductPage({ params }) {
  33.   const product = await getProduct(params.slug);
  34.   
  35.   return (
  36.     <div>
  37.       <nav aria-label="Breadcrumb">
  38.         <ol>
  39.           <li><a href="/">Home</a></li>
  40.           <li><a href="/products">Products</a></li>
  41.           <li><a href={`/products/${product.category}`}>{product.category}</a></li>
  42.           <li>{product.name}</li>
  43.         </ol>
  44.       </nav>
  45.       
  46.       <h1>{product.name}</h1>
  47.       {/* 产品内容 */}
  48.     </div>
  49.   );
  50. }
复制代码

总结与展望

Next.js 的路由系统已经从简单的文件系统路由发展成为功能强大且灵活的框架,能够满足现代 Web 应用的复杂需求。通过本文的探索,我们了解了 Next.js 路由的基础原理、高级配置和最佳实践。

从基础的静态和动态路由,到高级的并行路由、拦截路由和条件路由,Next.js 提供了丰富的工具来构建定制化的路由解决方案。结合中间件、性能优化技术和安全最佳实践,我们可以创建出既强大又可靠的 Web 应用。

随着 Next.js 的不断发展,我们可以期待更多创新的路由功能和改进。React Server Components、Suspense 和 Streaming SSR 等技术将继续塑造 Next.js 路由的未来,为开发者提供更强大的工具来构建下一代 Web 应用。

通过掌握 Next.js 路由配置的艺术,开发者可以充分发挥框架的潜力,创建出用户体验优秀、性能卓越且易于维护的现代化 Web 应用。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则