NextJS App Router:以root身份将所有路由重定向到两个嵌套的动态路由

dzhpxtsq  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(151)

我想知道是否有人可以帮助解决这个问题,我正在学习关于深度嵌套动态路由的应用程序路由器。
假设我有一个电子商务商店,它拥有多个商店,拥有自己的购物模式(提货和送货),并希望在URL中拥有商店ID和购物模式:www.shop.com/store/STOREID/sm/SHOPPINGMODE
当用户第一次访问www.shop.com时,他们首先会被问到他们想要的商店和购物模式(例如保存在本地的cookie),并且任何未来的访问都会将他们从根重定向到/store/STOREID/sm/SHOPPINGMODE url。
另一件事是,如果用户选择了一个商店,他们决定去www.shop.com/products,它会把他们重定向到www.shop.com/store/STOREID/sm/SHOPPINGMODE/products
所以基本上任何URL都应该附加store/STOREID/sm/SHOPPINGMODE

  • 如果是第一次访问:www.shop.com->选择商店-> www.shop.com/store/STOREID/sm/SHOPPINGMODE
  • 如果继续访视:www.shop.com-> www.shop.com/store/STOREID/sm/SHOPPINGMODE
  • 如果是第一次访问任何网址(如产品):www.shop.com/products->选择商店-> www.shop.com/store/STOREID/sm/SHOPPINGMODE/products
  • 如果继续访问任何URL(如产品):www.shop.com/products-> www.shop.com/store/STOREID/sm/SHOPPINGMODE/products

希望这是有意义的。什么是最有效的方式来实现这个场景?中间件?通过配置或页面重定向?其他的东西?
任何帮助将不胜感激!

x4shl7ld

x4shl7ld1#

我认为使用您提到的场景,以同样的方式使用SHOPPINGMODE和STOREID来验证用户是否登录会更有效。无论您的电子商务需要谁拥有这些信息,例如应用程序功能,验证中间件中的cookie可以保证它,例如:

// config matcher to not catch routes of static content or api and with store id and shopping mode

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)',
  '/((?!(store\/[0-9]*\/sm\/(pickup|delivery))).*)'
  ],
}
export function middleware(request: NextRequest) {

  const HOME = '/'

    // First verify if this cookies exist
  
  const HAS_STORE_ID = request.cookies.has('X_STORE_ID')
  const HAS_SHOPPING_MODE =          request.cookies.has('X_SHOPPING_MODE')
  
  if(HAS_STORE_ID && HAS_SHOPPING_MODE) {
  
  // Get values
  
  const STORE_ID = request.cookies.get('X_STORE_ID')
  const SHOPPING_MODE = request.cookies.get('X_SHOPPING_MODE')
  
  // You can verify if are valid values on database here or redirect later catching the error of page not found
  
  verifyValidStoreCookies(STORE_ID,SHOPPING_MODE)
  
  const url = `/store/${STORE_ID}/sm/${SHOPPING_MODE}`
  
  return NextResponse.rewrite(new URL(url, request.url))
    const { pathname } = req.nextUrl

  }
  
  if (HAS_STORE_ID) {
    response.cookies.delete('X_STORE_ID')

    return NextResponse.rewrite(new URL(HOME, request.url))

  }
   if (HAS_SHOPPING_MODE) {
        response.cookies.delete('X_SHOPPING_MODE')

    return NextResponse.rewrite(new URL(HOME, request.url))

  }
  
    return NextResponse.rewrite(new URL(HOME, request.url))

}

字符串
您可以使用路径搜索将任何路径附加到请求URL的末尾,并验证它们是否适用,例如:

const prefixes = ['/shop', '/products']

const { pathname } = request.nextUrl
 
  if (prefixes.some((prefix) => pathname.startsWith(prefix))) {
    const url = `/store/${STORE_ID}/sm/${SHOPPING_MODE}` + pathname
    return NextResponse.rewrite(new URL(url, request.url))
    ...
  }
 
  if (
    !pathname.endsWith('/') &&
    !pathname.match(/((?!\.products(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
  ) {
   ...
  }


你可以在这里查看更多的方法:https://nextjs.org/docs/app/building-your-application/routing/middleware
但它始终只是一种方法;它可以根据您的业务规则进行更改和改进。

相关问题