Using NProgress with Next.js

Published 9 days ago - 2 min read

Prerequisites

  • Next.js application with version 11 or higher

Getting started

First we'll need to install the NProgress npm module

npm install nprogress

And the types

npm install --save-dev @types/nprogress

Usage

Importing styles

To use the module, open your _app.tsx file. If you do not have an app file, checkout Next.js' docs.

Firstly we need import the required styles from nprogress.

pages/app.tsx
import "nprogress/nprogress.css";

const MyApp = () => {
    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";

const MyApp = () => {
  /* ... */
  React.useEffect(() => {
    const handleRouteState = () => 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

View an example here