Unverified Commit 2142b76e authored by Jan Potoms's avatar Jan Potoms Committed by GitHub

Normalize trailing slashes (#13333)

Co-authored-by: 's avatarJoe Haddad <joe.haddad@zeit.co>
Co-authored-by: 's avatarTim Neutkens <timneutkens@me.com>
parent b90fa0a3
---
description: Configure Next.js pages to resolve with or without a trailing slash.
---
# Trailing Slash
> **Warning**: This feature is **experimental and may not work as expected**.
> You must enable the `trailingSlash` experimental option to try it.
By default Next.js will redirect urls with trailing slashes to their counterpart without a trailing slash. For example `/about/` will redirect to `/about`. You can configure this behavior to act the opposite way, where urls without trailing slashes are redirected to their counterparts with trailing slashes.
Open `next.config.js` and add the `trailingSlash` config:
```js
module.exports = {
experimental: {
trailingSlash: true,
},
}
```
With this option set, urls like `/about` will redirect to `/about/`.
## Related
<div class="card">
<a href="/docs/api-reference/next.config.js/introduction.md">
<b>Introduction to next.config.js:</b>
<small>Learn more about the configuration file used by Next.js.</small>
</a>
</div>
...@@ -283,6 +283,10 @@ ...@@ -283,6 +283,10 @@
"title": "exportPathMap", "title": "exportPathMap",
"path": "/docs/api-reference/next.config.js/exportPathMap.md" "path": "/docs/api-reference/next.config.js/exportPathMap.md"
}, },
{
"title": "Trailing Slash",
"path": "/docs/api-reference/next.config.js/trailing-slash.md"
},
{ {
"title": "React Strict Mode", "title": "React Strict Mode",
"path": "/docs/api-reference/next.config.js/react-strict-mode.md" "path": "/docs/api-reference/next.config.js/react-strict-mode.md"
......
...@@ -806,6 +806,9 @@ export default async function getBaseWebpackConfig( ...@@ -806,6 +806,9 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir), 'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
} }
: {}), : {}),
'process.env.__NEXT_TRAILING_SLASH': JSON.stringify(
config.experimental.trailingSlash
),
'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify( 'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
config.exportTrailingSlash config.exportTrailingSlash
), ),
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
} from '../next-server/lib/utils' } from '../next-server/lib/utils'
import Router from './router' import Router from './router'
import { addBasePath } from '../next-server/lib/router/router' import { addBasePath } from '../next-server/lib/router/router'
import { normalizeTrailingSlash } from '../next-server/lib/router/normalize-trailing-slash'
function isLocal(href: string): boolean { function isLocal(href: string): boolean {
const url = parse(href, false, true) const url = parse(href, false, true)
...@@ -40,8 +41,21 @@ function memoizedFormatUrl(formatFunc: (href: Url, as?: Url) => FormatResult) { ...@@ -40,8 +41,21 @@ function memoizedFormatUrl(formatFunc: (href: Url, as?: Url) => FormatResult) {
} }
} }
function formatTrailingSlash(url: UrlObject): UrlObject {
return Object.assign({}, url, {
pathname:
url.pathname &&
normalizeTrailingSlash(url.pathname, !!process.env.__NEXT_TRAILING_SLASH),
})
}
function formatUrl(url: Url): string { function formatUrl(url: Url): string {
return url && typeof url === 'object' ? formatWithValidation(url) : url return (
url &&
formatWithValidation(
formatTrailingSlash(typeof url === 'object' ? url : parse(url))
)
)
} }
export type LinkProps = { export type LinkProps = {
......
...@@ -345,6 +345,20 @@ export default async function loadCustomRoutes( ...@@ -345,6 +345,20 @@ export default async function loadCustomRoutes(
loadRedirects(config), loadRedirects(config),
]) ])
redirects.unshift(
config.experimental.trailingSlash
? {
source: '/:path+',
destination: '/:path+/',
permanent: true,
}
: {
source: '/:path+/',
destination: '/:path+',
permanent: true,
}
)
return { return {
headers, headers,
rewrites, rewrites,
......
export function normalizeTrailingSlash(
path: string,
requireSlash?: boolean
): string {
if (path === '/') {
return path
} else if (path.endsWith('/')) {
return requireSlash ? path : path.slice(0, -1)
} else {
return requireSlash ? path + '/' : path
}
}
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
import { isDynamicRoute } from './utils/is-dynamic' import { isDynamicRoute } from './utils/is-dynamic'
import { getRouteMatcher } from './utils/route-matcher' import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex' import { getRouteRegex } from './utils/route-regex'
import { normalizeTrailingSlash } from './normalize-trailing-slash'
import getAssetPathFromRoute from './utils/get-asset-path-from-route' import getAssetPathFromRoute from './utils/get-asset-path-from-route'
const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || '' const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''
...@@ -43,8 +44,14 @@ function prepareUrlAs(url: Url, as: Url) { ...@@ -43,8 +44,14 @@ function prepareUrlAs(url: Url, as: Url) {
url = typeof url === 'object' ? formatWithValidation(url) : url url = typeof url === 'object' ? formatWithValidation(url) : url
as = typeof as === 'object' ? formatWithValidation(as) : as as = typeof as === 'object' ? formatWithValidation(as) : as
url = addBasePath(url) url = addBasePath(
as = as ? addBasePath(as) : as normalizeTrailingSlash(url, !!process.env.__NEXT_TRAILING_SLASH)
)
as = as
? addBasePath(
normalizeTrailingSlash(as, !!process.env.__NEXT_TRAILING_SLASH)
)
: as
return { return {
url, url,
......
...@@ -39,6 +39,7 @@ const defaultConfig: { [key: string]: any } = { ...@@ -39,6 +39,7 @@ const defaultConfig: { [key: string]: any } = {
exportTrailingSlash: false, exportTrailingSlash: false,
sassOptions: {}, sassOptions: {},
experimental: { experimental: {
trailingSlash: false,
cpus: Math.max( cpus: Math.max(
1, 1,
(Number(process.env.CIRCLE_NODE_TOTAL) || (Number(process.env.CIRCLE_NODE_TOTAL) ||
......
...@@ -67,6 +67,7 @@ import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp ...@@ -67,6 +67,7 @@ import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp
import { loadEnvConfig } from '../../lib/load-env-config' import { loadEnvConfig } from '../../lib/load-env-config'
import './node-polyfill-fetch' import './node-polyfill-fetch'
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin' import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
import { normalizeTrailingSlash } from '../lib/router/normalize-trailing-slash'
import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path' import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
...@@ -583,11 +584,14 @@ export default class Server { ...@@ -583,11 +584,14 @@ export default class Server {
type: 'route', type: 'route',
name: 'Catchall render', name: 'Catchall render',
fn: async (req, res, params, parsedUrl) => { fn: async (req, res, params, parsedUrl) => {
const { pathname, query } = parsedUrl let { pathname, query } = parsedUrl
if (!pathname) { if (!pathname) {
throw new Error('pathname is undefined') throw new Error('pathname is undefined')
} }
// next.js core assumes page path without trailing slash
pathname = normalizeTrailingSlash(pathname, false)
if (params?.path?.[0] === 'api') { if (params?.path?.[0] === 'api') {
const handled = await this.handleApiRequest( const handled = await this.handleApiRequest(
req as NextApiRequest, req as NextApiRequest,
......
...@@ -53,6 +53,13 @@ const runTests = (isDev = false) => { ...@@ -53,6 +53,13 @@ const runTests = (isDev = false) => {
expect($('#hello').text()).toContain('hello') expect($('#hello').text()).toContain('hello')
}) })
it('should load dynamic hybrid SSG/AMP page with trailing slash', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1/')
const $ = cheerio.load(html)
expect($('#use-amp').text()).toContain('no')
expect($('#hello').text()).toContain('hello')
})
it('should load dynamic hybrid SSG/AMP page with query', async () => { it('should load dynamic hybrid SSG/AMP page with query', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1?amp=1') const html = await renderViaHTTP(appPort, '/blog/post-1?amp=1')
const $ = cheerio.load(html) const $ = cheerio.load(html)
......
...@@ -26,12 +26,19 @@ function runTests() { ...@@ -26,12 +26,19 @@ function runTests() {
expect(data).toEqual({ slug: ['1'] }) expect(data).toEqual({ slug: ['1'] })
}) })
it('should 404 when catch-all with index and trailing slash', async () => { it('should return redirect when catch-all with index and trailing slash', async () => {
const res = await fetchViaHTTP(appPort, '/api/users/', null, {
redirect: 'manual',
})
expect(res.status).toBe(308)
})
it('should return data when catch-all with index and trailing slash', async () => {
const data = await fetchViaHTTP(appPort, '/api/users/', null, {}).then( const data = await fetchViaHTTP(appPort, '/api/users/', null, {}).then(
(res) => res.status (res) => res.ok && res.json()
) )
expect(data).toEqual(404) expect(data).toEqual({})
}) })
it('should return data when catch-all with index and no trailing slash', async () => { it('should return data when catch-all with index and no trailing slash', async () => {
......
...@@ -1002,12 +1002,10 @@ describe('Client Navigation', () => { ...@@ -1002,12 +1002,10 @@ describe('Client Navigation', () => {
await browser.close() await browser.close()
}) })
it('should 404 for <page>/', async () => { it('should not 404 for <page>/', async () => {
const browser = await webdriver(context.appPort, '/nav/about/') const browser = await webdriver(context.appPort, '/nav/about/')
expect(await browser.elementByCss('h1').text()).toBe('404') const text = await browser.elementByCss('p').text()
expect(await browser.elementByCss('h2').text()).toBe( expect(text).toBe('This is the about page.')
'This page could not be found.'
)
await browser.close() await browser.close()
}) })
......
...@@ -363,10 +363,9 @@ export default function (render, fetch) { ...@@ -363,10 +363,9 @@ export default function (render, fetch) {
expect($('h2').text()).toBe('This page could not be found.') expect($('h2').text()).toBe('This page could not be found.')
}) })
it('should 404 for <page>/', async () => { it('should not 404 for <page>/', async () => {
const $ = await get$('/nav/about/') const $ = await get$('/nav/about/')
expect($('h1').text()).toBe('404') expect($('.nav-about p').text()).toBe('This is the about page.')
expect($('h2').text()).toBe('This page could not be found.')
}) })
it('should should not contain a page script in a 404 page', async () => { it('should should not contain a page script in a 404 page', async () => {
......
...@@ -495,6 +495,14 @@ const runTests = (isDev = false) => { ...@@ -495,6 +495,14 @@ const runTests = (isDev = false) => {
pages404: true, pages404: true,
basePath: '', basePath: '',
redirects: [ redirects: [
{
destination: '/:path+',
regex: normalizeRegEx(
'^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$'
),
source: '/:path+/',
statusCode: 308,
},
{ {
destination: '/:lang/about', destination: '/:lang/about',
regex: normalizeRegEx( regex: normalizeRegEx(
......
...@@ -535,7 +535,7 @@ function runTests(dev) { ...@@ -535,7 +535,7 @@ function runTests(dev) {
basePath: '', basePath: '',
headers: [], headers: [],
rewrites: [], rewrites: [],
redirects: [], redirects: expect.arrayContaining([]),
dataRoutes: [ dataRoutes: [
{ {
namedDataRouteRegex: `^/_next/data/${escapeRegex( namedDataRouteRegex: `^/_next/data/${escapeRegex(
......
...@@ -8,8 +8,8 @@ import { ...@@ -8,8 +8,8 @@ import {
findPort, findPort,
nextBuild, nextBuild,
nextStart, nextStart,
fetchViaHTTP,
renderViaHTTP, renderViaHTTP,
fetchViaHTTP,
readNextBuildClientPageFile, readNextBuildClientPageFile,
getPageFileFromPagesManifest, getPageFileFromPagesManifest,
} from 'next-test-utils' } from 'next-test-utils'
...@@ -166,9 +166,22 @@ describe('Serverless Trace', () => { ...@@ -166,9 +166,22 @@ describe('Serverless Trace', () => {
expect(param).toBe('val') expect(param).toBe('val')
}) })
it('should 404 on API request with trailing slash', async () => { it('should reply with redirect on API request with trailing slash', async () => {
const res = await fetchViaHTTP(appPort, '/api/hello/') const res = await fetchViaHTTP(
expect(res.status).toBe(404) appPort,
'/api/hello/',
{},
{ redirect: 'manual' }
)
expect(res.status).toBe(308)
expect(res.headers.get('location')).toBe(
`http://localhost:${appPort}/api/hello`
)
})
it('should reply on API request with trailing slassh successfully', async () => {
const content = await renderViaHTTP(appPort, '/api/hello/')
expect(content).toMatch(/hello world/)
}) })
describe('With basic usage', () => { describe('With basic usage', () => {
......
...@@ -236,9 +236,22 @@ describe('Serverless', () => { ...@@ -236,9 +236,22 @@ describe('Serverless', () => {
expect(param).toBe('val') expect(param).toBe('val')
}) })
it('should 404 on API request with trailing slash', async () => { it('should reply with redirect on API request with trailing slash', async () => {
const res = await fetchViaHTTP(appPort, '/api/hello/') const res = await fetchViaHTTP(
expect(res.status).toBe(404) appPort,
'/api/hello/',
{},
{ redirect: 'manual' }
)
expect(res.status).toBe(308)
expect(res.headers.get('location')).toBe(
`http://localhost:${appPort}/api/hello`
)
})
it('should reply on API request with trailing slash successfully', async () => {
const content = await renderViaHTTP(appPort, '/api/hello/')
expect(content).toMatch(/hello world/)
}) })
it('should have the correct query string for a dynamic route', async () => { it('should have the correct query string for a dynamic route', async () => {
......
module.exports = {
experimental: {
// <placeholder>
},
}
export default function NotFound() {
return <div id="page-404">404</div>
}
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Page() {
const [isMounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
const router = useRouter()
return (
<div>
{isMounted ? <div id="hydration-marker" /> : null}
<div id="page-marker">/about.js</div>
<div id="router-pathname">{router.pathname}</div>
</div>
)
}
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Page() {
const [isMounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
const router = useRouter()
return (
<div>
{isMounted ? <div id="hydration-marker" /> : null}
<div id="page-marker">/catch-all/[...slug].js</div>
<div id="router-pathname">{router.pathname}</div>
</div>
)
}
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Page() {
const [isMounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
const router = useRouter()
return (
<div>
{isMounted ? <div id="hydration-marker" /> : null}
<div id="page-marker">/index.js</div>
<div id="router-pathname">{router.pathname}</div>
</div>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getServerSideProps({ query }) {
return {
props: { href: query.href || '/' },
}
}
export default function Linker({ href }) {
const router = useRouter()
const pushRoute = () => {
router.push(href)
}
return (
<div>
<Link href={href}>
<a id="link">link to {href}</a>
</Link>
<button id="route-pusher" onClick={pushRoute}>
push route {href}
</button>
</div>
)
}
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Page() {
const [isMounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
const router = useRouter()
return (
<div>
{isMounted ? <div id="hydration-marker" /> : null}
<div id="page-marker">/user/index.js</div>
<div id="router-pathname">{router.pathname}</div>
</div>
)
}
/* eslint-env jest */
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
import fs from 'fs-extra'
import {
fetchViaHTTP,
renderViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
nextStart,
} from 'next-test-utils'
import { join } from 'path'
jest.setTimeout(1000 * 60 * 2)
let app
let appPort
const appDir = join(__dirname, '../')
const nextConfig = join(appDir, 'next.config.js')
function testShouldRedirect(expectations) {
it.each(expectations)(
'%s should redirect to %s',
async (route, expectedLocation) => {
const res = await fetchViaHTTP(appPort, route, {}, { redirect: 'manual' })
expect(res.status).toBe(308)
const { pathname } = new URL(res.headers.get('location'))
expect(pathname).toBe(expectedLocation)
}
)
}
function testShouldResolve(expectations) {
it.each(expectations)(
'%s should resolve to %s, with router path %s',
async (route, expectedPage, expectedRouterPath) => {
const res = await fetchViaHTTP(appPort, route, {}, { redirect: 'error' })
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('#page-marker').text()).toBe(expectedPage)
expect($('#router-pathname').text()).toBe(expectedRouterPath)
}
)
it.each(expectations)(
'%s should client side render %s, with router path %s',
async (route, expectedPage, expectedRouterPath) => {
let browser
try {
browser = await webdriver(appPort, route)
await browser.waitForElementByCss('#hydration-marker')
const text = await browser.elementByCss('#page-marker').text()
expect(text).toBe(expectedPage)
const routerPathname = await browser
.elementByCss('#router-pathname')
.text()
expect(routerPathname).toBe(expectedRouterPath)
} finally {
if (browser) await browser.close()
}
}
)
}
function testLinkShouldRewriteTo(expectations) {
it.each(expectations)(
'%s should have href %s',
async (href, expectedHref) => {
const content = await renderViaHTTP(appPort, `/linker?href=${href}`)
const $ = cheerio.load(content)
expect($('#link').attr('href')).toBe(expectedHref)
}
)
it.each(expectations)(
'%s should navigate to %s',
async (href, expectedHref) => {
let browser
try {
browser = await webdriver(appPort, `/linker?href=${href}`)
await browser.elementByCss('#link').click()
await browser.waitForElementByCss('#hydration-marker')
const { pathname } = new URL(await browser.eval('window.location.href'))
expect(pathname).toBe(expectedHref)
} finally {
if (browser) await browser.close()
}
}
)
it.each(expectations)(
'%s should push route to %s',
async (href, expectedHref) => {
let browser
try {
browser = await webdriver(appPort, `/linker?href=${href}`)
await browser.elementByCss('#route-pusher').click()
await browser.waitForElementByCss('#hydration-marker')
const { pathname } = new URL(await browser.eval('window.location.href'))
expect(pathname).toBe(expectedHref)
} finally {
if (browser) await browser.close()
}
}
)
}
function testWithTrailingSlash() {
testShouldRedirect([
['/about/', '/about'],
['/catch-all/hello/world/', '/catch-all/hello/world'],
])
testShouldResolve([
// visited url, expected page, expected router path
['/', '/index.js', '/'],
['/about', '/about.js', '/about'],
[
'/catch-all/hello/world',
'/catch-all/[...slug].js',
'/catch-all/[...slug]',
],
])
testLinkShouldRewriteTo([
['/', '/'],
['/about', '/about'],
['/about/', '/about'],
])
}
function testWithoutTrailingSlash() {
testShouldRedirect([
['/about', '/about/'],
['/catch-all/hello/world', '/catch-all/hello/world/'],
])
testShouldResolve([
// visited url, expected page, expected router path
['/', '/index.js', '/'],
['/about/', '/about.js', '/about'],
[
'/catch-all/hello/world/',
'/catch-all/[...slug].js',
'/catch-all/[...slug]',
],
])
testLinkShouldRewriteTo([
['/', '/'],
['/about', '/about/'],
['/about/', '/about/'],
])
}
describe('Trailing slashes', () => {
describe('dev mode, trailingSlash: false', () => {
let origNextConfig
beforeAll(async () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
origNextConfig.replace('// <placeholder>', 'trailingSlash: false')
)
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
testWithTrailingSlash()
})
describe('dev mode, trailingSlash: true', () => {
let origNextConfig
beforeAll(async () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
origNextConfig.replace('// <placeholder>', 'trailingSlash: true')
)
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
testWithoutTrailingSlash()
})
describe('production mode, trailingSlash: false', () => {
let origNextConfig
beforeAll(async () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
origNextConfig.replace('// <placeholder>', 'trailingSlash: false')
)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
testWithTrailingSlash()
it('should have a redirect in the routesmanifest', async () => {
const manifest = await fs.readJSON(
join(appDir, '.next', 'routes-manifest.json')
)
expect(manifest).toEqual(
expect.objectContaining({
redirects: expect.arrayContaining([
expect.objectContaining({
source: '/:path+/',
destination: '/:path+',
statusCode: 308,
}),
]),
})
)
})
})
describe('production mode, trailingSlash: true', () => {
let origNextConfig
beforeAll(async () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
origNextConfig.replace('// <placeholder>', 'trailingSlash: true')
)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
testWithoutTrailingSlash()
it('should have a redirect in the routesmanifest', async () => {
const manifest = await fs.readJSON(
join(appDir, '.next', 'routes-manifest.json')
)
expect(manifest).toEqual(
expect.objectContaining({
redirects: expect.arrayContaining([
expect.objectContaining({
source: '/:path+',
destination: '/:path+/',
statusCode: 308,
}),
]),
})
)
})
})
})
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