Next.js add top progress bar fetch and router events using NProgress

Posted on February 19, 2022

Here are the steps to show the top progress bar like Youtube.

First, install nprogress package using the below command

npm install nprogress

Then create components/TopProgressBar.js and add the following code

import Router from "next/router";
import NProgress from "nprogress";

let timer;
let state;
let activeRequests = 0;
const delay = 5;

const load = () => {
  if (state === "loading") {
    return;
  }

  state = "loading";

  timer = setTimeout(function () {
    NProgress.start();
  }, delay);
}

const stop = () => {
  if (activeRequests > 0) {
    return;
  }

  state = "stop";

  clearTimeout(timer);
  NProgress.done();
}

Router.events.on("routeChangeStart", load);
Router.events.on("routeChangeComplete", stop);
Router.events.on("routeChangeError", stop);

const originalFetch = window.fetch;
window.fetch = async function (...args) {
  if (activeRequests === 0) {
    load();
  }

  activeRequests++;

  try {
    const response = await originalFetch(...args);
    return response;
  } catch (error) {
    return Promise.reject(error);
  } finally {
    activeRequests -= 1;
    if (activeRequests === 0) {
      stop();
    }
  }
};

export default function () {
  return null;
}

Finally, add this component to _app.js

import "nprogress/nprogress.css";

const TopProgressBar = dynamic(() => {
    return import("components/TopProgressBar");
}, { ssr: false });

export default function MyApp({ Component, pageProps }) {
    return <>
        <TopProgressBar />
        <Component {...pageProps} />
    </>
}

That's it. It will show the top progress bar automatically.

to join this conversation on Samprix.Already have an account? Sign in to comment
SPONSORS