Unverified Commit 5b2c845e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure API routes are not available under the locale (#26629)

This ensures API routes are not available under the locale path since API routes don't need to be localized and we don't provide the locale to the API in any way currently so the user wouldn't be aware if the localized API route was visited instead of the non-localized. 

Fixes: https://github.com/vercel/next.js/issues/25790

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
parent c5751fa6
......@@ -465,6 +465,13 @@ export default class Server {
pathname: localePathResult.pathname,
})
;(req as any).__nextStrippedLocale = true
if (
localePathResult.pathname === '/api' ||
localePathResult.pathname.startsWith('/api/')
) {
return this.render404(req, res, parsedUrl)
}
}
// If a detected locale is a domain specific locale and we aren't already
......
......@@ -37,7 +37,7 @@ async function addDefaultLocaleCookie(browser) {
}
export function runTests(ctx) {
it.only('should have domainLocales available on useRouter', async () => {
it('should have domainLocales available on useRouter', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath || '/'}`)
expect(
JSON.parse(await browser.elementByCss('#router-domain-locales').text())
......@@ -1146,44 +1146,54 @@ export function runTests(ctx) {
for (const locale of locales) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || ''}${
locale === 'en-US' ? '' : `/${locale}`
}/api/hello`,
`${ctx.basePath || ''}/${locale}/api/hello`,
undefined,
{
redirect: 'manual',
}
)
const data = await res.json()
expect(data).toEqual({
hello: true,
query: {},
})
expect(res.status).toBe(404)
}
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || ''}/api/hello`
)
const data = await res.json()
expect(data).toEqual({
hello: true,
query: {},
})
})
it('should visit dynamic API route directly correctly', async () => {
for (const locale of locales) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || ''}${
locale === 'en-US' ? '' : `/${locale}`
}/api/post/first`,
`${ctx.basePath || ''}/${locale}/api/post/first`,
undefined,
{
redirect: 'manual',
}
)
const data = await res.json()
expect(data).toEqual({
post: true,
query: {
slug: 'first',
},
})
expect(res.status).toBe(404)
}
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || ''}/api/post/first`
)
const data = await res.json()
expect(data).toEqual({
post: true,
query: {
slug: 'first',
},
})
})
it('should rewrite to API route correctly', async () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment