Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/bold-jars-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-hono-server": minor
---

✨ feat: Added optional production graceful shutdown for bun adapter.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,20 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
* {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
*/
customBunServer?: Serve.Options<unknown, string>;
/**
* Callback executed after server has closed and all inflight requests completed,
* before process exit. Only applicable in production mode.
*
* @example
* ```ts
* export default createHonoServer({
* onGracefulShutdown: async () => {
* await db.close();
* },
* });
* ```
*/
onGracefulShutdown?: () => Promise<void> | void;
/**
* Customize the serve static options
*/
Expand Down
6 changes: 6 additions & 0 deletions examples/bun/graceful-shutdown/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules

/.cache
/build
.env
.react-router
116 changes: 116 additions & 0 deletions examples/bun/graceful-shutdown/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Bun Graceful Shutdown Example

This example demonstrates the graceful shutdown feature of the Bun adapter for `react-router-hono-server`.

## Features

- ✅ Graceful shutdown hook (`onGracefulShutdown`)
- ✅ Signal handler setup (SIGTERM, SIGINT)
- ✅ Clean resource cleanup before process exit
- ✅ Production-ready pattern

## How It Works

### 1. Server Configuration

In [app/server.ts](./app/server.ts), simply configure the server with a graceful shutdown callback:

```ts
export default createHonoServer({
onGracefulShutdown: async () => {
console.log('🧹 Running cleanup tasks...');
// Your cleanup logic here (close DB connections, etc.)
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('✅ Cleanup complete!');
},
});
```

**That's it!** The Bun adapter automatically registers SIGTERM and SIGINT signal handlers when you provide an `onGracefulShutdown` callback. No additional setup needed.

### 2. Shutdown Flow

When you send a SIGTERM or SIGINT signal (e.g., Ctrl+C):

1. Automatic signal handler is triggered
2. Server stops accepting new connections
3. Existing inflight requests complete
4. `onGracefulShutdown` callback executes
5. Process exits cleanly

## Running the Example

### Development

```bash
bun install
bun run dev
```

### Production

```bash
bun run build
bun run start
```

Then press `Ctrl+C` to test the graceful shutdown. You should see:

```
📡 Received SIGINT, shutting down gracefully...
Initiating graceful shutdown...
Server stopped, all requests completed
🧹 Running cleanup tasks...
✅ Cleanup complete!
Cleanup callback completed
👋 Shutdown complete
```

## Key Files

- [app/server.ts](./app/server.ts) - Server configuration with graceful shutdown callback
- [app/routes/_index.tsx](./app/routes/_index.tsx) - Demo page explaining the feature

## Notes

- The `onGracefulShutdown` callback only runs in **production mode**
- During development, the callback is ignored
- Signal handlers (SIGTERM, SIGINT) are automatically registered in production
- The server waits indefinitely for inflight connections to complete

## Deployment

When deploying to production environments (Docker, Kubernetes, etc.), ensure:

1. Your container/orchestrator sends SIGTERM for graceful shutdown
2. Allow sufficient time for graceful shutdown before force kill
3. Configure health checks to stop sending traffic during shutdown

### Docker Example

```dockerfile
FROM oven/bun:latest
WORKDIR /app
COPY . .
RUN bun install
RUN bun run build
CMD ["bun", "./scripts/start.ts"]

# Important: Use exec form to handle signals properly
# OR use: ENTRYPOINT ["bun", "./scripts/start.ts"]
```

### Kubernetes Example

```yaml
spec:
containers:
- name: app
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 5"]
terminationGracePeriodSeconds: 30
```

This gives the app time to finish graceful shutdown before Kubernetes force-kills the pod.
31 changes: 31 additions & 0 deletions examples/bun/graceful-shutdown/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "react-router";

import "./tailwind.css";

export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}

export default function Root() {
return <Outlet />;
}
4 changes: 4 additions & 0 deletions examples/bun/graceful-shutdown/app/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";

export default flatRoutes() satisfies RouteConfig;
31 changes: 31 additions & 0 deletions examples/bun/graceful-shutdown/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { Route } from "./+types/_index";

export function meta({}: Route.MetaArgs) {
return [
{ title: "Graceful Shutdown Demo" },
{ name: "description", content: "Bun adapter graceful shutdown example" },
];
}

export default function Index() {
return (
<div className="flex h-screen items-center justify-center">
<div className="flex flex-col items-center gap-8 text-center">
<h1 className="text-4xl font-bold">Graceful Shutdown for Bun Demo</h1>
<p className="text-lg text-gray-600 max-w-md">
This example demonstrates the graceful shutdown feature of the Bun adapter. Press{" "}
<kbd className="px-2 py-1 bg-gray-100 rounded">Ctrl+C</kbd> in the terminal to test graceful shutdown.
</p>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 max-w-md">
<h2 className="font-semibold mb-2">What happens on shutdown:</h2>
<ol className="text-left space-y-1 text-sm">
<li>1. Server stops accepting new connections</li>
<li>2. Existing requests complete</li>
<li>3. Cleanup callback executes</li>
<li>4. Process exits cleanly</li>
</ol>
</div>
</div>
</div>
);
}
8 changes: 8 additions & 0 deletions examples/bun/graceful-shutdown/app/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createHonoServer } from "react-router-hono-server/bun";

export default createHonoServer({
onGracefulShutdown: async () => {
// Simulate cleanup operations (e.g., closing database connections)
await new Promise((resolve) => setTimeout(resolve, 1000));
},
});
3 changes: 3 additions & 0 deletions examples/bun/graceful-shutdown/app/tailwind.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
Loading
Loading