Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook into NextJS server startup

Tags:

config

next.js

How do I hook into the startup of a NextJS server so that I can do one-off initialization?

There's a discussion here but so far no solution.

like image 257
Guy Avatar asked Apr 21 '26 08:04

Guy


2 Answers

You can use instrumention.ts(or .js) file from nextjs official documentation

This is basically, we export a function named register in a file called instrumention (js/ts) in root directory of your project. In the src/ directory if you use one. Nextjs looks for the file and calls the function whenever server instance is bootstrapped.

  1. First add a config to you next.config.js file like below

next.config.js

/** @type {import('next').NextConfig} */
    
const nextConfig = {
    experimental: { instrumentationHook: true },
};

module.exports = nextConfig;
  1. Then write any logic you want to run on server startup Below is a sample instrumention.ts file. I wrote register function with a simple scheduled task which logs datetime on every 2 secs.

instrumentation.ts

export function register() {
  setInterval(() => console.log(new Date()), 2000)
}

Save the file and restart the server. The output only updates on restarting the server. else the previous code will run if you had one in instrumentation.ts file.

now you can see the output below.

Output Output image

Read the full doc here

like image 188
Praveenkumar M Avatar answered Apr 23 '26 21:04

Praveenkumar M


Just add your code to the next.config.js file.

Something like this should do the trick:

//next.config.js
//imports

module.exports = async (phase, { defaultConfig }) => {
    const nextConfig = {...}
    console.log("Executes at server startup")
    return nextConfig
}
like image 45
Fabian Svensson Avatar answered Apr 23 '26 21:04

Fabian Svensson