Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure middleware is output in standalone mode #32967

Merged
merged 1 commit into from
Jan 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions packages/next/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1400,6 +1400,13 @@ export default async function build(
'utf8'
)

const middlewareManifest: MiddlewareManifest = JSON.parse(
await promises.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
'utf8'
)
)

const outputFileTracingRoot =
config.experimental.outputFileTracingRoot || dir

Expand All @@ -1412,7 +1419,8 @@ export default async function build(
distDir,
pageKeys,
outputFileTracingRoot,
requiredServerFiles.config
requiredServerFiles.config,
middlewareManifest
)
})
}
Expand Down Expand Up @@ -1961,13 +1969,6 @@ export default async function build(
)
}

const middlewareManifest: MiddlewareManifest = JSON.parse(
await promises.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
'utf8'
)
)

await promises.writeFile(
path.join(
distDir,
Expand Down Expand Up @@ -2032,7 +2033,8 @@ export default async function build(
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'pages'
)
),
{ overwrite: true }
)
}

Expand Down
49 changes: 37 additions & 12 deletions packages/next/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
SSG_GET_INITIAL_PROPS_CONFLICT,
SERVER_PROPS_GET_INIT_PROPS_CONFLICT,
SERVER_PROPS_SSG_CONFLICT,
MIDDLEWARE_ROUTE,
} from '../lib/constants'
import prettyBytes from '../lib/pretty-bytes'
import { recursiveReadDir } from '../lib/recursive-readdir'
Expand All @@ -40,6 +41,7 @@ import { NextConfigComplete } from '../server/config-shared'
import isError from '../lib/is-error'
import { recursiveDelete } from '../lib/recursive-delete'
import { Sema } from 'next/dist/compiled/async-sema'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'

const { builtinModules } = require('module')
const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/
Expand Down Expand Up @@ -1156,7 +1158,8 @@ export async function copyTracedFiles(
distDir: string,
pageKeys: string[],
tracingRoot: string,
serverConfig: { [key: string]: any }
serverConfig: { [key: string]: any },
middlewareManifest: MiddlewareManifest
) {
const outputPath = path.join(distDir, 'standalone')
const copiedFiles = new Set()
Expand Down Expand Up @@ -1202,6 +1205,23 @@ export async function copyTracedFiles(
}

for (const page of pageKeys) {
if (MIDDLEWARE_ROUTE.test(page)) {
const { files } =
middlewareManifest.middleware[page.replace(/\/_middleware$/, '')]

for (const file of files) {
const originalPath = path.join(distDir, file)
const fileOutputPath = path.join(
outputPath,
path.relative(tracingRoot, distDir),
file
)
await fs.mkdir(path.dirname(fileOutputPath), { recursive: true })
await fs.copyFile(originalPath, fileOutputPath)
}
continue
}

const pageFile = path.join(
distDir,
'server',
Expand All @@ -1226,16 +1246,7 @@ const NextServer = require('next/dist/server/next-server').default
const http = require('http')
const path = require('path')

const nextServer = new NextServer({
dir: path.join(__dirname),
dev: false,
conf: ${JSON.stringify({
...serverConfig,
distDir: `./${path.relative(dir, distDir)}`,
})},
})

const handler = nextServer.getRequestHandler()
let handler

const server = http.createServer(async (req, res) => {
try {
Expand All @@ -1246,12 +1257,26 @@ const server = http.createServer(async (req, res) => {
res.end('internal server error')
}
})
const currentPort = process.env.PORT || 3000
const currentPort = parseInt(process.env.PORT, 10) || 3000

server.listen(currentPort, (err) => {
if (err) {
console.error("Failed to start server", err)
process.exit(1)
}
const addr = server.address()
const nextServer = new NextServer({
hostname: 'localhost',
port: currentPort,
dir: path.join(__dirname),
dev: false,
conf: ${JSON.stringify({
...serverConfig,
distDir: `./${path.relative(dir, distDir)}`,
})},
})
handler = nextServer.getRequestHandler()

console.log("Listening on port", currentPort)
})
`
Expand Down
16 changes: 16 additions & 0 deletions test/production/required-server-files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,22 @@ describe('should set-up next', () => {
if (server) await killApp(server)
})

it('should output middleware correctly', async () => {
// the middleware-runtime is located in .next/static/chunks so ensure
// the folder is present
expect(
await fs.pathExists(join(next.testDir, 'standalone/.next/static/chunks'))
).toBe(true)
expect(
await fs.pathExists(
join(
next.testDir,
'standalone/.next/server/pages/middleware/_middleware.js'
)
)
).toBe(true)
})

it('should output required-server-files manifest correctly', async () => {
expect(requiredFilesManifest.version).toBe(1)
expect(Array.isArray(requiredFilesManifest.files)).toBe(true)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export async function middleware(req) {
return new Response('hello from middleware')
}