Using NProgress with Next.js

How to add a simple loading bar to a Next.js app

10 min read

views

Prerequisites

  • Next.js application with version 11 or higher

Getting started

Firstly, we must install the NProgress npm module

npm install nprogress
bash

And its types

npm install --save-dev @types/nprogress
bash

Usage

Importing styles

Custom app

If you do not have an _app file yet, you can copy this template below. This example comes from Next.js' docs.

Open template
pages/_app.tsx
export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}
tsx

To use the module, open your _app.tsx file. We must import the required styles from nprogress.

pages/_app.tsx
import "nprogress/nprogress.css";
 
export default function MyApp({ Component, pageProps, router }) {
  return; /* ... */
}
tsx

Router events

We'll add a useEffect in our component and add 2 handlers to handle routeChangeStart and routeChangeComplete. More info about router events.

pages/_app.tsx
import * as React from "react";
import NProgress from "nprogress";
 
export default function MyApp({ Component, pageProps, router }) {
  /* ... */
  React.useEffect(() => {
    const handleRouteStart = () => NProgress.start();
    const handleRouteDone = () => NProgress.done();
 
    router.events.on("routeChangeStart", handleRouteStart);
    router.events.on("routeChangeComplete", handleRouteDone);
    router.events.on("routeChangeError", handleRouteDone);
 
    return () => {
      // Make sure to remove the event handler on unmount!
      router.events.off("routeChangeStart", handleRouteStart);
      router.events.off("routeChangeComplete", handleRouteDone);
      router.events.off("routeChangeError", handleRouteDone);
    };
  }, []);
  /* ... */
}
tsx

Done

That's it! Start your dev server and see the changes!

Examples