|
| 1 | +// Adapted from @sls-next/lambda-at-edge (v1.2.0-alpha.3) |
| 2 | +// See: https://github.com/danielcondemarin/serverless-next.js/blob/57142970b08e6bc3faf0fc70749b3b0501ad7869/packages/lambda-at-edge/src/lib/expressifyDynamicRoute.ts#L4 |
| 3 | + |
| 4 | +const CATCH_ALL_REGEX = /\/\[\.{3}(.*)\](.json)?$/; |
| 5 | +const OPTIONAL_CATCH_ALL_REGEX = /\/\[{2}\.{3}(.*)\]{2}(.json)?$/; |
| 6 | +const DYNAMIC_PARAMETER_REGEX = /\/\[(.*?)\]/g; |
| 7 | + |
| 8 | +// Convert dynamic NextJS routes into their Netlify-equivalent |
| 9 | +// Note that file endings (.json) must be removed for catch-all and optional |
| 10 | +// catch-all routes to work. That's why the regexes defined above include |
| 11 | +// the (.json)? option |
| 12 | +const getNetlifyRoutes = (nextRoute) => { |
| 13 | + let netlifyRoutes = [nextRoute]; |
| 14 | + |
| 15 | + // If the route is an optional catch-all route, we need to add a second |
| 16 | + // Netlify route for the base path (when no parameters are present). |
| 17 | + // The file ending must be present! |
| 18 | + if (nextRoute.match(OPTIONAL_CATCH_ALL_REGEX)) { |
| 19 | + netlifyRoutes.push(nextRoute.replace(OPTIONAL_CATCH_ALL_REGEX, "$2")); |
| 20 | + } |
| 21 | + |
| 22 | + // Replace catch-all, e.g., [...slug] |
| 23 | + netlifyRoutes = netlifyRoutes.map((route) => |
| 24 | + route.replace(CATCH_ALL_REGEX, "/:$1/*") |
| 25 | + ); |
| 26 | + |
| 27 | + // Replace optional catch-all, e.g., [[...slug]] |
| 28 | + netlifyRoutes = netlifyRoutes.map((route) => |
| 29 | + route.replace(OPTIONAL_CATCH_ALL_REGEX, "/*") |
| 30 | + ); |
| 31 | + |
| 32 | + // Replace dynamic parameters, e.g., [id] |
| 33 | + netlifyRoutes = netlifyRoutes.map((route) => |
| 34 | + route.replace(DYNAMIC_PARAMETER_REGEX, "/:$1") |
| 35 | + ); |
| 36 | + |
| 37 | + return netlifyRoutes; |
| 38 | +}; |
| 39 | + |
| 40 | +module.exports = getNetlifyRoutes; |
0 commit comments