How to check a condition before starting NextJS app?

I have a NextJS (version 13.2.4) project. Whenever I want to run the app, I execute the following:

npm run dev

However, there is a requirement that I need to check whether a certain condition is met to allow the app to start; otherwise, exit the app before starting it.

The condition is just to check if a file exists in the machine that is running it.

How to achieve such flow?

>Solution :

You can achieve this by creating a custom script that checks for the condition (file existence) before starting the Next.js app. Here are the steps you can follow:

  1. Create a Custom Script:

    In your package.json file, you can add a custom script that checks for the condition before starting the Next.js app.

    "scripts": {
        "start-custom": "node checkCondition.js && next dev"
  2. Create the Check Condition Script:

    Create a file named checkCondition.js in the root of your project. In this file, you’ll write a script to check if the file exists. If it exists, the script should return true; otherwise, it should return false.

    const fs = require('fs');
    function checkCondition() {
        try {
            fs.accessSync('/path/to/your/file', fs.constants.F_OK);
            return true;
        } catch (err) {
            return false;
    if (!checkCondition()) {
        console.error('Condition not met. Exiting...');

    Make sure to replace /path/to/your/file with the actual path to the file you want to check for.

  3. Run the Custom Script:

    Now, you can run your custom script using:

    npm run start-custom

This script will first check the condition using checkCondition.js. If the condition is not met (file doesn’t exist), it will print an error message and exit the process. If the condition is met, it will proceed to start the Next.js app.

Leave a Reply