Report this

What is the reason for this report?

How To Restart Your Node.js Apps Automatically with Nodemon

Updated on October 28, 2025
English
How To Restart Your Node.js Apps Automatically with Nodemon

Introduction

When developing a Node.js application, you must stop and restart the process every time you make a file change for those changes to take effect. This manual step adds friction and repetition to the development workflow.

You can remove this extra step by using nodemon, a command-line interface (CLI) utility that automatically restarts your Node.js application when it detects file changes in your project directory. It is a wrapper for the node command that watches the file system and restarts the process.

In this article, you will install nodemon, use it to run a sample Express project, and configure its behavior with command-line options and a nodemon.json file. You will also learn how nodemon functions, why it is a development-only tool, and how to troubleshoot common issues.

Key Takeaways:

  • Its primary purpose is to speed up development by restarting your app on file changes. Production environments need a process manager (like PM2 or systemd) that restarts the app on crashes and manages stability.
  • The recommended way to use nodemon is to install it as a local development dependency (npm install nodemon --save-dev) and run it via the scripts section of your package.json (e.g., "dev": "nodemon server.js").
  • While command-line flags work, a nodemon.json file is a cleaner, sharable way to manage settings. You can define specific watch paths, ignore patterns, and extensions to monitor.
  • nodemon only watches specific extensions by default. By default, nodemon only restarts for changes to .js, .mjs, and .json files. If you want it to watch other files, like .env or .ts, you must explicitly add them to the ext (extensions) configuration.
  • If nodemon isn’t restarting, it’s likely one of two issues: you’re editing a file it isn’t watching (fix with the ext config) or your text editor uses “safe write,” which requires the legacy watch flag (-L).
  • If your application starts and immediately crashes in a continuous loop, it is not a nodemon bug. It means your application has an error on startup. Check the terminal for the error message from your code.
  • You don’t need to stop and start nodemon to force a restart. You can simply type rs into the terminal where nodemon is running and press Enter.

Prerequisites

To follow this tutorial, you will need:

  • Node.js and npm: This tutorial was tested with Node.js version 22.20.0 and npm version 10.9.3. You can follow this guide to install Node.js and npm on your local machine.

How Does Nodemon Work?

nodemon wraps your application’s execution (e.g., node server.js) and monitors the project directory for file changes.

By default, it watches the current working directory. When it detects a file with a specified extension (like .js, .mjs, or .json) is added, modified, or deleted, it automatically performs one action: it sends a SIGUSR2 signal to the child process (your application) to terminate it, and then it immediately starts a new process to run your application again.

This file-watching mechanism relies on the operating system’s built-in file system event APIs (like fs.watch in Node.js, which uses inotify on Linux or FSEvents on macOS). This is very efficient and does not require constant polling, which would use more CPU. However, some text editors or virtualized file systems can interfere with these events, requiring a legacy polling method (-L) as a fallback.

Understanding Nodemon: Development vs. Production

nodemon is a tool intended exclusively for local development. Its purpose is to watch for file changes and restart the application, which is useful when you are actively writing and testing code. This creates a fast, convenient feedback loop for the developer.

This behavior is not suitable for a production environment. Nodemon’s file-watching mechanism adds resource overhead that is unnecessary in production, where code is not expected to change “on the fly.” In production, you should not be changing files on the server in a way that requires an automatic restart; changes should be part of a structured deployment process. If your production application stops due to an unhandled exception, nodemon will not restart it, leading to downtime.

Instead, a production server requires a process manager, such as PM2 or systemd. A process manager’s job is to ensure the application remains running by automatically restarting it if it crashes due to an error, not when a file is modified. Process managers also handle other production-critical tasks like log management and running applications in a cluster for better performance.

Step 1 — Installing Nodemon

You can install nodemon in two ways: globally on your system or locally within your project.

Global Installation

A global installation makes the nodemon command available from any directory in your terminal.

  1. npm install -g nodemon

A local installation adds nodemon as a devDependency to your project. This is the recommended approach because it versions the tool with your project. This ensures that all developers on your team are using the same version of nodemon.

  1. npm install nodemon --save-dev

When you install a package locally, you cannot run it directly from the command line with nodemon. Instead, you must run it using one of two methods:

  1. Using npx: The npx command, which comes with npm, executes packages. You would run npx nodemon.
  2. Using npm Scripts: You can add nodemon to your package.json file’s scripts section. This is the most common and practical method, which you will use in the next steps.

Step 2 — Setting Up a Sample Express Project

Let’s create a small Express server to demonstrate how nodemon works.

First, create a new directory for your project, navigate into it, and initialize a new package.json file.

  1. mkdir nodemon-demo
  2. cd nodemon-demo
  3. npm init -y

Next, install express as a dependency and nodemon as a development dependency.

  1. npm install express
  2. npm install nodemon --save-dev

Now, create a file named server.js in your project’s root directory.

  1. nano server.js

Open server.js in your text editor and add the following code:

server.js
const express = require('express');
const app = express();
const port = 3000;

app.listen(port, ()=> console.log(`Dolphin app listening on port ${port}!`))

This code creates a simple Express server that listens on port 3000 and responds to requests at the root URL (/) with a message.

Save and close the file.

Step 3 — Running Your App with Nodemon

Now that you have a server, you can run it with nodemon. The most effective way to use nodemon in a project is by adding it to your package.json scripts.

Open your package.json file. You will see a scripts section that looks like this:

package.json
  // ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  // ...

Modify the scripts section to add two new scripts: start and dev.

  • start: This script will run the application normally using node. This is typically used for production.
  • dev: This script will run the application using nodemon. This is used for development.
package.json
  // ...
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  // ...

Save the package.json file. You can now start your server in development mode by running the dev script:

  1. npm run dev

nodemon will start and wrap your node application. You will see output similar to the following:

Output
[nodemon] 3.1.10 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Dolphin app listening on port 3000!

nodemon reports that it is watching all files (*.*) with the default extensions (.js, .mjs, .json).

Testing the Auto-Reload

While nodemon is running, open your server.js file in a new terminal and change the response message.

server.js
// ...
app.listen(port, ()=> console.log(`Shark app listening on port ${port}!`))
// ...

Save the file. When you return to your terminal, you will see that nodemon has automatically detected the change and restarted the server.

Output
[nodemon] restarting due to changes... [nodemon] starting `node server.js` Shark app listening on port 3000!

Step 4 — Configuring Nodemon with Command-Line Options

You can modify behavior of nodemon by passing command-line options. These can be added directly to your npm script in package.json.

Here are some of the most common configuration options:

Option Description
--watch <dir> Specifies one or more directories or files to watch. Use multiple --watch flags for multiple paths.
--ext <extensions> Specifies the file extensions to watch (e.g., js,ts,json).
--ignore <pattern> Ignores specific files, patterns, or directories (e.g., *.test.js, public/).
--exec <command> Executes a different binary instead of node, such as ts-node for TypeScript.
--delay <seconds> Adds a delay (in seconds) before restarting. This can “debounce” multiple file-save events.

Imagine you are working on a TypeScript project and you want nodemon to:

  1. Watch only the src directory.
  2. Watch for files ending in .ts.
  3. Ignore all test files, which end in .test.ts.
  4. Execute the file using ts-node.

Your dev script in package.json would look something like this:

package.json
  // ...
  "scripts": {
    "dev": "nodemon --watch 'src' --ext 'ts' --ignore '*.test.ts' --exec 'ts-node' src/server.ts"
  },
  // ...

The command break down is as follows:

  • --watch 'src': Only watch for changes inside the src folder.
  • --ext 'ts': Only watch files with the .ts extension.
  • --ignore '*.test.ts': Do not restart when a test file is changed.
  • --exec 'ts-node': Use the ts-node binary to run the file instead of node.
  • src/server.ts: The entry point file for the application.

Step 5 — Using a Configuration File

Command-line flags can become long and difficult to manage. A better solution is to use a configuration file. nodemon automatically looks for a nodemon.json file in your project’s root directory.

Let’s create a configuration file for the Express project from Step 2. A common requirement is to make nodemon watch for changes in .env files (which store environment variables) or to ignore specific folders.

First, create the nodemon.json file in the root folder of your project:

  1. touch nodemon.json

Now, let’s configure it to:

  • Explicitly watch the server.js file and any .env files.
  • Watch for new file extensions: .js, .json, and .env.
  • Ignore the node_modules directory (though nodemon does this by default, it’s good practice to be explicit).
  • Add a 1-second delay before restarting to “debounce” multiple quick saves.

Open nodemon.json and add the following configuration:

nodemon.json
{
  "watch": [
    "server.js",
    ".env"
  ],
  "ext": "js,json,env",
  "ignore": [
    "node_modules/"
  ],
  "delay": 1
}

With this file, your package.json script can be simplified:

package.json
  // ...
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  // ...

Now, when you run npm run dev, nodemon will find and use these settings. If you create a .env file and make a change, nodemon will detect it and restart the server, which is useful for applications that need to load new environment variables on startup.

You can also place this configuration inside your package.json file under a nodemonConfig key, but using a separate nodemon.json file is often preferred for better organization.

Step 6 — Manually Restarting

Sometimes you may need to force a restart of your application, even if no file has changed (for example, if a database connection was lost). While nodemon is running, you can type rs in the terminal and press ENTER to manually trigger a restart.

[nodemon] manual restart
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Dolphin app listening on port 3000!

Step 7 — Troubleshooting Common Issues

Let’s look at few common problems you might encounter when using nodemon.

Error: nodemon: command not found

  • Cause: You installed nodemon locally (with npm install nodemon --save-dev) but are trying to run it directly from your terminal as nodemon server.js. Your shell does not know where to find the locally installed binary.

  • Solution 1 (Recommended): Run the command through an npm script, as shown in Step 3 (npm run dev). npm scripts automatically find locally installed binaries.

  • Solution 2: Use npx to execute the local package: npx nodemon server.js.

  • Solution 3: Install nodemon globally using npm install -g nodemon.

nodemon Isn’t Restarting on File Changes

  • Cause 1: Wrong File Extension. You are saving a file that nodemon does not watch by default, such as a .env or .sql file. By default, nodemon only watches .js, .mjs, and .json.

  • Solution 1: Use the --ext flag or the ext property in nodemon.json to add your desired extensions. For example, to also watch .env files:

    nodemon.json
    {
      "ext": "js,mjs,json,env"
    }
    
  • Cause 2: File Path is Ignored. The file you are changing is in a directory that is ignored by default (like node_modules) or by one of your own configuration rules.

  • Solution 2: Check your ignore patterns in your nodemon.json file.

  • Cause 3: Using an Editor with “Safe Write”. Some text editors and IDEs (like JetBrains IDEs or Vim) use an “atomic save” or “safe write” feature. This feature saves changes to a temporary file and then renames it, which can interfere with the file system event listeners that nodemon uses.

  • Solution 3: Use nodemon’s “legacy watch” mode by adding the -L flag. This mode polls for file changes instead of relying on file system events.

    package.json
    "scripts": {
      "dev": "nodemon -L server.js"
    },
    

Application Crashes in a Restart Loop

  • Cause: You start nodemon, and it immediately restarts, over and over, without you changing any files. This happens when your application has an error that causes it to crash immediately upon starting. nodemon sees the process exit, so it restarts it, only for the application to crash again, creating an infinite loop.

    Output
    [nodemon] starting `node server.js` /home/user/nodemon-demo/server.js:12 app.listen(port, () => { ^ TypeError: app.listen is not a function [nodemon] app crashed - waiting for file changes before starting...

    In older versions, nodemon might loop. In newer versions (like the output above), nodemon is often smart enough to detect this and will print an “app crashed” message and wait for a file change before trying again.

  • Solution: Read the error message in your terminal carefully. The problem is not with nodemon; it is with your application code. In the example output, the error is a TypeError: app.listen is not a function. You must fix this underlying bug in your server.js file. Once you save a fix, nodemon will detect the change and restart the application correctly.

High CPU Usage or Slow Restarts

  • Cause 1: Watching node_modules. By default, nodemon is configured to ignore the node_modules directory. However, a misconfiguration in your nodemon.json (e.g., an incorrect watch path that accidentally includes node_modules) could cause nodemon to watch thousands of files, leading to high CPU usage.

  • Solution 1: Ensure your ignore patterns are correct. Add "ignore": ["node_modules/"] to your nodemon.json to be explicit.

  • Cause 2: Legacy Watch Mode. Using the -L (legacy watch) flag forces nodemon to poll every file for changes instead of using the operating system’s native file-watching events. This is much less efficient and can significantly increase CPU load, especially on large projects.

  • Solution 2: Only use the -L flag if you have no other choice (e.g., in a problematic virtual machine or container environment). Try to fix the underlying file system event issue first, such as by disabling “safe write” in your text editor.

FAQs

1. What is Nodemon used for in Node.js?

Nodemon is a command-line utility used during local development to automatically restart your Node.js application when it detects file changes in your project directory.

Its main purpose is to speed up the development workflow. By default, when you make a change to a Node.js script, you must manually stop the server (with Ctrl-C) and restart it (with node server.js) to see your changes. Nodemon wraps your application, watches for file modifications, and automatically handles this restart process for you.

2. How do I install and run Nodemon globally?

You can install nodemon globally using npm with the -g flag:

  1. npm install -g nodemon

Once installed, you can run it from any directory in your terminal by replacing the node command with nodemon:

  1. nodemon app.js

While global installation is convenient, installing nodemon locally in your project as a development dependency is the recommended approach. This ensures all developers on your project use the same version.

  1. npm install nodemon --save-dev

You can then run the local version by adding it to your package.json scripts:

package.json
"scripts": {
  "dev": "nodemon server.js"
}

And running it with:

  1. npm run dev

3. Why isn’t Nodemon restarting my app automatically?

This usually happens for one of three reasons:

  1. You are editing a file extension that nodemon does not watch. By default, nodemon only watches for files with .js, .mjs, and .json extensions. If you are editing a file like .env, .css, or .sql, nodemon will ignore it.

    • Solution: Use the --ext flag to specify all extensions you want to watch.

      1. nodemon --ext "js,mjs,env,graphql" server.js
  2. Your text editor is using “safe write” or “atomic saves”. Some text editors and IDEs (like JetBrains products or Vim) save files by writing to a temporary file and then renaming it. This process can interfere with nodemon’s file-system event listeners.

    • Solution: Use nodemon’s legacy watch mode (-L), which polls for changes instead of listening for events.

      1. nodemon -L server.js
  3. The file you are changing is in an ignored directory. nodemon ignores certain directories by default, such as node_modules/ and .git/. If your file is in a custom-ignored path, nodemon will not restart. Check your nodemon.json configuration for any ignore patterns.

4. How can I use a custom Nodemon configuration file?

You can create a nodemon.json file in the root directory of your project. nodemon will automatically find and use this file for its configuration, which is much cleaner than using long command-line flags.

For example, instead of this command:

  1. nodemon --watch src/ --watch .env --ext "js,env" --delay 1`

You can create a nodemon.json file with this content:

nodemon.json
{
  "watch": [
    "src/",
    ".env"
  ],
  "ext": "js,env",
  "delay": 1
}

Now, you can simply run nodemon (or npm run dev if you’re using npm scripts), and it will load these settings.

Alternatively, you can add this same configuration directly into your package.json file under a nodemonConfig key.

5. What’s the difference between Nodemon and PM2?

The main difference is their intended environment: nodemon is for development, and PM2 is for production.

  • nodemon restarts your application when you save a file. Its goal is to speed up coding and testing.
  • PM2 is a process manager that restarts your application when it crashes. Its goal is to ensure your application stays online and is reliable for users.

Here is a side-by-side comparison:

Feature nodemon (Development) PM2 (Production)
Primary Goal Developer productivity. Application uptime and reliability.
Restart Trigger A file is modified or saved. The application process crashes or the server reboots.
Key Features File watching, manual restart (rs). Crash recovery, clustering, log management, startup service.

6. Can I use Nodemon with TypeScript or ES Modules?

Yes. For TypeScript, you need to tell nodemon to use a TypeScript execution engine like ts-node or tsx. You can do this with the --exec flag or an execMap in your configuration.

Here is a nodemon.json example for a TypeScript project:

nodemon.json
{
  "watch": ["src/"],
  "ext": "ts,json",
  "exec": "ts-node src/server.ts"
}

For ES Modules (.mjs files or "type": "module" in package.json), nodemon works automatically with modern versions of Node.js. It watches .mjs files by default, and if you use "type": "module", it will correctly run your .js files as ES Modules.

7. How do I limit which files Nodemon watches?

You can control which files nodemon watches using the watch and ignore configurations.

  • watch: This option specifies which directories or files nodemon should watch. By default, it watches the current directory (.). If you specify a watch path, it will only watch that path.
  • ignore: This option specifies files or patterns to exclude from watching. nodemon ignores node_modules/ and .git/ by default.

You can use these in a nodemon.json file for precise control. For example, if you want nodemon to only watch your src/routes directory and your .env file, but ignore all test files within that directory:

nodemon.json
{
  "watch": [
    "src/routes/",
    ".env"
  ],
  "ignore": [
    "*.test.js"
  ],
  "ext": "js,env"
}

Conclusion

nodemon is a simple utility that significantly improves the Node.js development experience. By automating the server restart process, it removes a tedious manual step, allowing you to focus on writing code.

In this tutorial, you learned how nodemon functions by watching the file system, how to install it, and how to run a Node.js application with it using npm scripts. You configured its behavior using both command-line flags and a nodemon.json configuration file. You also explored the critical difference between nodemon for development and a process manager for production, and learned how to troubleshoot common issues.

For more information on all available features, you can consult the official nodemon documentation.

For more Node.js tutorials, check out the following articles:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Alligator
Alligator
Author
See author profile

Alligator.io is a developer-focused resource that offers tutorials and insights on a wide range of modern front-end technologies, including Angular 2+, Vue.js, React, TypeScript, Ionic, and JavaScript.

Bradley Kouchi
Bradley Kouchi
Editor
See author profile

Former Technical Editor at DigitalOcean. Expertise in areas including Vue.js, CSS, React, and more.

Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Category:
Tags:

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

nodemonConfig key in package.json and nodemon.json both take parameters for “delay” key in milliseconds rather than seconds.

praise to nodemon but maybe try alternativ https://github.com/jbystronski/watcher

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.