Skip to content

Instantly share code, notes, and snippets.

@composite
Created January 8, 2026 12:42
Show Gist options
  • Select an option

  • Save composite/36956faacebcbb7cbf0d468f09458673 to your computer and use it in GitHub Desktop.

Select an option

Save composite/36956faacebcbb7cbf0d468f09458673 to your computer and use it in GitHub Desktop.
Hono + Vite server with graceful scheduler start and stop integration
import type { Plugin } from 'vite';
import type { NodeBuildOptions } from '@hono/vite-build/node';
import buildPlugin from '@hono/vite-build';
const nodeBuildPlugin = (pluginOptions?: NodeBuildOptions): Plugin => {
const port = pluginOptions?.port ?? 3000;
return {
...buildPlugin({
...{
entryContentBeforeHooks: [
async () => {
// SPA 라우팅 시스템 상 staticPath 가 쓸모 없으므로 로직 삭제
return "import { serveStatic } from '@hono/node-server/serve-static'\n";
},
],
entryContentAfterHooks: [
async (appName) => {
let code = '';
code += `import { serve } from '@hono/node-server';
const isotime = () => {
const now = new Date();
now.setHours(now.getHours() + 9);
return now.toISOString().replace('Z', '+09:00');
};
const scheduler = {
list: typeof modules === 'undefined' ? [] : Object.values(modules).map(({ scheduler }) => scheduler).filter(Boolean),
start: () => {
if (scheduler.list.length) console.log(\`[\${isotime()}]\`, 'Starting scheduler...');
return Promise.all(scheduler.list.map(({ start }) => typeof start === 'function' ? start() : Promise.resolve()));
},
stop: () => {
if (scheduler.list.length) console.log(\`[\${isotime()}]\`, 'Stopping scheduler...');
return Promise.all(scheduler.list.map(({ stop }) => typeof stop === 'function' ? stop() : Promise.resolve()));
},
};
const server = serve({
fetch: ${appName}.fetch,
port: ${port.toString()}
}, ({ address, port }) => {
scheduler.start().then(() => { scheduler.list.length && console.log(\`[\${isotime()}]\`, 'Started scheduler...'); });
console.log(\`[\${isotime()}]\`, 'Starting server', \`http://\${address.startsWith('::') ? 'localhost' : address}:\${port}\`);
});
process.on('SIGINT', () => {
scheduler.stop().finally(() => {
console.log(\`[\${isotime()}]\`, 'Stopping server...');
server.close();
process.exit(0);
});
});
process.on('SIGTERM', () => {
scheduler.stop().finally(() => server.close((err) => {
if (err) {
console.error(\`[\${isotime()}]\`, 'Stopping server error:', err)
process.exit(1)
}
console.log(\`[\${isotime()}]\`, 'Stopping server...');
process.exit(0)
}));
});
`;
return code;
},
],
},
...pluginOptions,
}),
name: '@hono/vite-build/node',
};
};
export default nodeBuildPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment