Commit 36aabe05 authored by Luis Fernando Alvarez D's avatar Luis Fernando Alvarez D Committed by Tim Neutkens

Show warning if next export detects an API route (#8257)

* Throw error if next export detects an api route

* Moved the test to the export tests

* Added missing comma

* Move the API route comment

* Add comma after replace

* Show a warning instead
parent f01af7ce
# API routes in Static export
#### Why This Warning Occurred
An `exportPathMap` path was matched to an API route. `next export` will not prerender API routes to HTML.
#### Possible Ways to Fix It
Remove any paths using API routes from your `exportPathMap` in `next.config.js`.
### Useful Links
- [Static HTML export](https://github.com/zeit/next.js#static-html-export)
...@@ -4,6 +4,7 @@ import { recursiveCopy } from '../lib/recursive-copy' ...@@ -4,6 +4,7 @@ import { recursiveCopy } from '../lib/recursive-copy'
import mkdirpModule from 'mkdirp' import mkdirpModule from 'mkdirp'
import { resolve, join } from 'path' import { resolve, join } from 'path'
import { existsSync, readFileSync } from 'fs' import { existsSync, readFileSync } from 'fs'
import chalk from 'chalk'
import loadConfig, { import loadConfig, {
isTargetLikeServerless isTargetLikeServerless
} from 'next-server/dist/server/config' } from 'next-server/dist/server/config'
...@@ -36,7 +37,6 @@ export default async function (dir, options, configuration) { ...@@ -36,7 +37,6 @@ export default async function (dir, options, configuration) {
const threads = options.threads || Math.max(cpus().length - 1, 1) const threads = options.threads || Math.max(cpus().length - 1, 1)
const distDir = join(dir, nextConfig.distDir) const distDir = join(dir, nextConfig.distDir)
const subFolders = nextConfig.exportTrailingSlash const subFolders = nextConfig.exportTrailingSlash
let apiPage = false
if (!options.buildExport && nextConfig.target !== 'server') { if (!options.buildExport && nextConfig.target !== 'server') {
throw new Error( throw new Error(
...@@ -62,19 +62,12 @@ export default async function (dir, options, configuration) { ...@@ -62,19 +62,12 @@ export default async function (dir, options, configuration) {
for (const page of pages) { for (const page of pages) {
// _document and _app are not real pages // _document and _app are not real pages
// _error is exported as 404.html later on // _error is exported as 404.html later on
const isApiRoute = page.match(API_ROUTE) // API Routes are Node.js functions
// Warn about API pages export
if (isApiRoute && !apiPage) {
apiPage = true
log(` API pages are not supported in export`)
}
if ( if (
page === '/_document' || page === '/_document' ||
page === '/_app' || page === '/_app' ||
page === '/_error' || page === '/_error' ||
isApiRoute page.match(API_ROUTE)
) { ) {
continue continue
} }
...@@ -149,10 +142,24 @@ export default async function (dir, options, configuration) { ...@@ -149,10 +142,24 @@ export default async function (dir, options, configuration) {
}) })
exportPathMap['/404.html'] = exportPathMap['/404.html'] || { page: '/_error' } exportPathMap['/404.html'] = exportPathMap['/404.html'] || { page: '/_error' }
const exportPaths = Object.keys(exportPathMap) const exportPaths = Object.keys(exportPathMap)
const filteredPaths = exportPaths.filter(
// Remove API routes
route => !exportPathMap[route].page.match(API_ROUTE)
)
const hasApiRoutes = exportPaths.length !== filteredPaths.length
// Warn if the user defines a path for an API page
if (hasApiRoutes) {
log(
chalk.yellow(
' API pages are not supported by next export. https://err.sh/zeit/next.js/api-routes-static-export'
)
)
}
const progress = !options.silent && createProgress(exportPaths.length) const progress = !options.silent && createProgress(filteredPaths.length)
const chunks = exportPaths.reduce((result, route, i) => { const chunks = filteredPaths.reduce((result, route, i) => {
const worker = i % threads const worker = i % threads
if (!result[worker]) { if (!result[worker]) {
result[worker] = { paths: [], pathMap: {} } result[worker] = { paths: [], pathMap: {} }
......
...@@ -10,7 +10,6 @@ import { ...@@ -10,7 +10,6 @@ import {
renderViaHTTP, renderViaHTTP,
nextBuild, nextBuild,
nextStart, nextStart,
runNextCommand,
File File
} from 'next-test-utils' } from 'next-test-utils'
import json from '../big.json' import json from '../big.json'
...@@ -286,17 +285,6 @@ function runTests (serverless = false) { ...@@ -286,17 +285,6 @@ function runTests (serverless = false) {
} }
}) })
if (!serverless) {
it('should warn about API export', async () => {
const { stdout } = await runNextCommand(['export', appDir], {
stdout: true,
stderr: true
})
expect(stdout).toContain('API pages are not supported in export')
})
}
it('should return data on dynamic optional nested route', async () => { it('should return data on dynamic optional nested route', async () => {
const data = await fetchViaHTTP( const data = await fetchViaHTTP(
appPort, appPort,
......
...@@ -37,6 +37,7 @@ module.exports = phase => { ...@@ -37,6 +37,7 @@ module.exports = phase => {
query: { text: 'this file has an extension' } query: { text: 'this file has an extension' }
}, },
'/query': { page: '/query', query: { a: 'blue' } }, '/query': { page: '/query', query: { a: 'blue' } },
// API route
'/blog/nextjs/comment/test': { page: '/blog/[post]/comment/[id]' } '/blog/nextjs/comment/test': { page: '/blog/[post]/comment/[id]' }
} }
} // end exportPathMap } // end exportPathMap
......
export default (req, res) => {
res.send('Hello World')
}
/* eslint-env jest */
import { join } from 'path'
import { File, runNextCommand } from 'next-test-utils'
export default function (context) {
describe('API routes export', () => {
const nextConfig = new File(join(context.appDir, 'next.config.js'))
beforeEach(() => {
nextConfig.replace('// API route', `'/data': { page: '/api/data' },`)
})
afterEach(() => {
nextConfig.restore()
})
it('Should throw if a route is matched', async () => {
const outdir = join(context.appDir, 'outApi')
const { stdout } = await runNextCommand(
['export', context.appDir, '--outdir', outdir],
{ stdout: true }
)
expect(stdout).toContain(
'https://err.sh/zeit/next.js/api-routes-static-export'
)
})
})
}
...@@ -19,6 +19,7 @@ import dev from './dev' ...@@ -19,6 +19,7 @@ import dev from './dev'
import { promisify } from 'util' import { promisify } from 'util'
import fs from 'fs' import fs from 'fs'
import dynamic from './dynamic' import dynamic from './dynamic'
import apiRoutes from './api-routes'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
...@@ -96,4 +97,5 @@ describe('Static Export', () => { ...@@ -96,4 +97,5 @@ describe('Static Export', () => {
browser(context) browser(context)
dev(devContext) dev(devContext)
dynamic(context) dynamic(context)
apiRoutes(context)
}) })
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