|
1 | 1 | /** |
2 | | - * Removes trailing slashes from URLs. |
| 2 | + * Adds trailing slashes to URLs. |
3 | 3 | * |
4 | | - * This middleware only runs in development to maintain consistent behavior. |
5 | | - * In production, Vercel handles this redirect via vercel.json. |
| 4 | + * We use middleware to correctly handle all the cases, since Vercel doesn't handle it properly for nuxt app. |
6 | 5 | * |
7 | | - * - /package/vue/ → /package/vue |
8 | | - * - /docs/getting-started/?query=value → /docs/getting-started?query=value |
| 6 | + * - /package/vue → /package/vue/ |
| 7 | + * - /docs/getting-started?query=value → /docs/getting-started/?query=value |
9 | 8 | */ |
10 | 9 | export default defineNuxtRouteMiddleware(to => { |
11 | | - if (import.meta.prerender) return |
| 10 | + // request is marked as prerender for build and server ISR |
| 11 | + // ignore rewrite for build prerender only |
| 12 | + if (import.meta.prerender && process.env.NUXT_STAGE === 'build') return |
| 13 | + |
| 14 | + // ignore for package-code (file viewer shouldn't relate on trailing slash) and api routes |
| 15 | + if ( |
| 16 | + to.path.startsWith('/package-code/') || |
| 17 | + to.path.startsWith('/api/') || |
| 18 | + to.path.endsWith('/_payload.json') |
| 19 | + ) |
| 20 | + return |
12 | 21 |
|
13 | 22 | if (import.meta.server) { |
14 | 23 | const event = useRequestEvent() |
15 | | - const url = event?.node.req.originalUrl || event?.node.req.url || '' |
16 | 24 |
|
17 | | - if (url.includes('/_payload.json')) return |
18 | | - } |
| 25 | + // requests to /page-path/_payload.json are handled with to.path="/page-path", so we use the original url to check properly |
| 26 | + const urlRaw = event?.node.req.originalUrl || event?.node.req.url || '' |
| 27 | + const originalUrl = new URL(urlRaw, 'http://npmx.dev') |
19 | 28 |
|
20 | | - if (to.path.startsWith('/package-code/') || to.path.startsWith('/api/')) return |
| 29 | + if (originalUrl.pathname.includes('/_payload.json') || originalUrl.pathname.endsWith('/')) |
| 30 | + return |
| 31 | + } |
21 | 32 |
|
22 | 33 | if (to.path !== '' && !to.path.endsWith('/')) { |
23 | 34 | return navigateTo( |
|
0 commit comments