#Run custom function once on server start in production with adapter:node

4 messages · Page 1 of 1 (latest)

unborn apex
#

since I can remember I'm in search of a way to run a custom function once on server startup in production (function can be anything like creating some directories if not exist or making a few symlinks)
so far I wasn't able to find any reliable info about that, I would consider it an absolute basic feature to have

zenith cliffBOT
#

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
}

[Building an Adapter]

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'],
        });
      },
    },
  };
}

[Building an Adapter]

The knowledge sources do not explicitly mention how to modify the official @astrojs/node adapter's internal entrypoint directly. However, the documented way to control server startup behavior in Astro is through this start function in a custom server entrypoint [Building an Adapter].

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: