Commit bbcb448e authored by Lukáš Huvar's avatar Lukáš Huvar Committed by kodiakhq[bot]

Fix index.js for API routes (#8112)

This fixes the problem with `/pages/api/index.js` not creating serverless function. Fixes #8111 
parent eae1f6b7
import { join } from 'path'
import { stringify } from 'querystring'
import { PAGES_DIR_ALIAS, DOT_NEXT_ALIAS } from '../lib/constants'
import { PAGES_DIR_ALIAS, DOT_NEXT_ALIAS, API_ROUTE } from '../lib/constants'
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
type PagesMapping = {
......@@ -68,7 +68,7 @@ export function createEntrypoints(
Object.keys(pages).forEach(page => {
const absolutePagePath = pages[page]
const bundleFile = page === '/' ? '/index.js' : `${page}.js`
const isApiRoute = bundleFile.startsWith('/api/')
const isApiRoute = bundleFile.match(API_ROUTE)
const bundlePath = join('static', buildId, 'pages', bundleFile)
......
......@@ -3,6 +3,7 @@ import { join } from 'path'
import { parse } from 'querystring'
import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST } from 'next-server/constants'
import { isDynamicRoute } from 'next-server/dist/lib/router/utils'
import { API_ROUTE } from '../../../lib/constants'
export type ServerlessLoaderQuery = {
page: string
......@@ -39,7 +40,7 @@ const nextServerlessLoader: loader.Loader = function() {
'/'
)
if (page.startsWith('/api/')) {
if (page.match(API_ROUTE)) {
return `
${
isDynamicRoute(page)
......
......@@ -15,6 +15,9 @@ export const NEXT_PROJECT_ROOT_DIST_SERVER = join(
'server'
)
// Regex for API routes
export const API_ROUTE = /^\/api(?:\/|$)/
// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,
// we have to use a private alias
export const PAGES_DIR_ALIAS = 'private-next-pages'
......
export default (req, res) => {
res.send('Index should work')
}
......@@ -45,6 +45,27 @@ function runTests (serverless = false) {
killApp(app)
})
it('should work with index api', async () => {
if (serverless) {
const port = await findPort()
const resolver = require(join(appDir, '.next/serverless/pages/api.js'))
.default
const server = createServer(resolver).listen(port)
const res = await fetchViaHTTP(port, '/api')
const text = await res.text()
server.close()
expect(text).toEqual('Index should work')
} else {
const text = await fetchViaHTTP(appPort, '/api', null, {}).then(
res => res.ok && res.text()
)
expect(text).toEqual('Index should work')
}
})
it('should return custom error', async () => {
const data = await fetchViaHTTP(appPort, '/api/error', null, {})
const json = await data.json()
......
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