Page Loading Progress Bar in Next.js

Page Loading Progress Bar in Next.js

Posted on 27th October 2020

Last updated on 24th February 2022

2 min read

3407 views

In this post I’ll show how to implement a page loading indicator like in YouTube, GitHub and this site.

The example above is running with the cache disabled and the "Slow 3G" preset.

To get started, install the @badrap/bar-of-progress dependency.

yarn add @badrap/bar-of-progress

Then create the _app.js file in pages if you haven’t done so already.

pages/_app.js

const MyApp = ({ Component, pageProps }) => {
  return <Component {...pageProps} />;
};

export default MyApp;

Next import the bar-of-progress dependency into _app.js and declare a new progress bar.

pages/_app.js

import ProgressBar from "@badrap/bar-of-progress";

const progress = new ProgressBar({
  size: 2,
  color: "#38a169",
  className: "bar-of-progress",
  delay: 100,
});

const MyApp = ({ Component, pageProps }) => {
  return <Component {...pageProps} />;
};

export default MyApp;

After that we need to access the router object with the useRouter hook.

pages/_app.js

import ProgressBar from "@badrap/bar-of-progress";
import { useRouter } from "next/router";

const progress = new ProgressBar({
  size: 2,
  color: "#38a169",
  className: "bar-of-progress",
  delay: 100,
});

const MyApp = ({ Component, pageProps }) => {
  const router = useRouter();

  return <Component {...pageProps} />;
};

export default MyApp;

We’ll be using the router object’s events to control the progress bar.

pages/_app.js

import ProgressBar from "@badrap/bar-of-progress";
import { useRouter } from "next/router";
import { useEffect } from 'react';

const progress = new ProgressBar({
  size: 2,
  color: "#38a169",
  className: "bar-of-progress",
  delay: 100,
});

const MyApp = ({ Component, pageProps }) => {
  const router = useRouter();

  useEffect(() => {
    router.events.on("routeChangeStart", progress.start);
    router.events.on("routeChangeComplete", progress.finish);
    router.events.on("routeChangeError", progress.finish);

    return () => {
      router.events.off("routeChangeStart", progress.start);
      router.events.off("routeChangeComplete", progress.finish);
      router.events.off("routeChangeError", progress.finish);
    };
  }, [router]);

  return <Component {...pageProps} />;
};

export default MyApp;

If all goes well, you should be seeing a progress bar on the top of your site while transitioning between pages.

Sometimes the progress bar might be hidden behind another element, as was the case in this site.

To solve it all you have to do is increase the z-index of the progress bar in your css.

.bar-of-progress {
  z-index: 50;
}

The class name is the className property we gave when declaring the progress bar.

const progress = new ProgressBar({
  size: 2,
  color: "#38a169",
  className: "bar-of-progress",
  delay: 100,
});

If you enjoyed this post please leave a like or two below!!!