Skip to content

Commit dbcffe1

Browse files
committed
fix: improve trailing slash detection logic
1 parent 9d32dbb commit dbcffe1

File tree

2 files changed

+23
-12
lines changed

2 files changed

+23
-12
lines changed

app/middleware/trailing-slash.global.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,34 @@
11
/**
2-
* Removes trailing slashes from URLs.
2+
* Adds trailing slashes to URLs.
33
*
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.
65
*
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
98
*/
109
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
1221

1322
if (import.meta.server) {
1423
const event = useRequestEvent()
15-
const url = event?.node.req.originalUrl || event?.node.req.url || ''
1624

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')
1928

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+
}
2132

2233
if (to.path !== '' && !to.path.endsWith('/')) {
2334
return navigateTo(

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
"url": "https://roe.dev"
1111
},
1212
"scripts": {
13-
"build": "nuxt build",
13+
"build": "NUXT_STAGE=build nuxt build",
1414
"build:lunaria": "node ./lunaria/lunaria.ts",
15-
"build:test": "NODE_ENV=test pnpm build",
15+
"build:test": "NUXT_STAGE=build NODE_ENV=test pnpm build",
1616
"dev": "nuxt dev",
1717
"dev:docs": "pnpm run --filter npmx-docs dev --port=3001",
1818
"i18n:check": "node scripts/compare-translations.ts",

0 commit comments

Comments
 (0)