From fd3a9259fdb66f37531b11f8ee09b3391bda71cb Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Sat, 26 Jun 2021 11:59:20 -0500 Subject: [PATCH] Ensure API routes are not available under the locale --- .../next/next-server/server/next-server.ts | 7 +++ test/integration/i18n-support/test/shared.js | 48 +++++++++++-------- 2 files changed, 36 insertions(+), 19 deletions(-) diff --git a/packages/next/next-server/server/next-server.ts b/packages/next/next-server/server/next-server.ts index 54594d035482e..0df8098887933 100644 --- a/packages/next/next-server/server/next-server.ts +++ b/packages/next/next-server/server/next-server.ts @@ -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 diff --git a/test/integration/i18n-support/test/shared.js b/test/integration/i18n-support/test/shared.js index 98b0ec4f1a3f8..7411de3a52bd1 100644 --- a/test/integration/i18n-support/test/shared.js +++ b/test/integration/i18n-support/test/shared.js @@ -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 () => {