Using NProgress with Next.js

September 08, 2021

2 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

And its types

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

Usage

Importing styles

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

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} />;
}
pages/_app.tsx
import "nprogress/nprogress.css";

export default function MyApp({ Component, pageProps }) {
  return /* ... */
}

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 Router from "next/router";
import NProgress from "nprogress"

export default function MyApp({ Component, pageProps }) {
  /* ... */
  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);
    };
  }, []);
  /* ... */
};

Done

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

Examples