Skip to content
Open
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
25 changes: 16 additions & 9 deletions docs/01-app/02-guides/self-hosting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -253,16 +253,23 @@ You can set the env variable `NEXT_MANUAL_SIG_HANDLE` to `true` and then registe
}
```

```js filename="pages/_document.js"
```js filename="app/layout.tsx"
if (process.env.NEXT_MANUAL_SIG_HANDLE) {
process.on('SIGTERM', () => {
console.log('Received SIGTERM: cleaning up')
process.exit(0)
})
process.on('SIGINT', () => {
console.log('Received SIGINT: cleaning up')
process.exit(0)
})
let sigHandled = false
const handleSig = () => {
if (sigHandled) return
sigHandled = true

console.log('Received SIGINT/SIGTERM: cleaning up')

// Run clean up

// Trigger Next.js graceful shutdown
process.env.NEXT_MANUAL_SIG_HANDLE = false
process.emit('SIGTERM')
}
process.on('SIGTERM', handleSig)
process.on('SIGINT', handleSig)
}
```

Expand Down
10 changes: 5 additions & 5 deletions packages/next/src/server/lib/start-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,9 @@ export async function startServer(
let cleanupStarted = false
let closeUpgraded: (() => void) | null = null
const cleanup = () => {
// Allow the graceful termination to be manually configurable
if (process.env.NEXT_MANUAL_SIG_HANDLE) return

if (cleanupStarted) {
// We can get duplicate signals, e.g. when `ctrl+c` is used in an
// interactive shell (i.e. bash, zsh), the shell will recursively
Expand Down Expand Up @@ -422,11 +425,8 @@ export async function startServer(
}

// Make sure commands gracefully respect termination signals (e.g. from Docker)
// Allow the graceful termination to be manually configurable
if (!process.env.NEXT_MANUAL_SIG_HANDLE) {
process.on('SIGINT', cleanup)
process.on('SIGTERM', cleanup)
}
process.on('SIGINT', cleanup)
process.on('SIGTERM', cleanup)

const initResult = await getRequestHandlers({
dir,
Expand Down
Loading