#Run custom function once on server start in production with adapter:node
4 messages · Page 1 of 1 (latest)
Hi @unborn apex. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Astro, when building a custom adapter or extending one like @astrojs/node, you can use the Server Entrypoint to run custom logic when the server starts.
The Adapter API provides a start function that is specifically designed for hosts where the server must be started manually. This function is called once when the bundle script is run in production [Building an Adapter].
Implementing Startup Logic
To run a custom function once on startup (such as creating directories or symlinks), you can include that logic within the start function of your server entrypoint:
import { App } from 'astro/app';
export function start(manifest) {
const app = new App(manifest);
// Your custom startup logic runs here, once
console.log("Running custom startup tasks...");
myCustomStartupFunction();
// Example of starting a fetch listener (or a Node server)
addEventListener('fetch', event => {
event.respondWith(
app.render(event.request)
);
});
}
function myCustomStartupFunction() {
// Perform tasks like creating directories or symlinks
}
Configuring the Adapter
In your integration, you must ensure that your adapter points to this server entrypoint. You do this by calling setAdapter within the astro:config:done hook:
// my-adapter.mjs
export default function createIntegration() {
return {
name: 'my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: 'my-adapter',
serverEntrypoint: 'my-adapter/server.js', // Path to the file containing start()
exports: ['handler'],
});
},
},
};
}