Sometimes when you transition from one route to another, it takes a little time to do so due to different factors. Behind the scenes, it may be rendering a complex page component or doing an API call. In such cases, the app looks like it has frozen for some seconds and then suddenly transitions to the next route. This results in a poor UX. In such cases, it is better to add a progress bar to your app which gives your users a sense that something is loading.
In this tutorial, you’ll learn to implement a progress bar in a Next.js app.
Contents
Installing NProgress
The first thing you need to do is to install nprogress NPM package.
To install nprogress, run the following command in your terminal:
npm i nprogress
Understanding Basic Usage
In the pages/_app.js, import the following modules:
import Router from 'next/router'
import NProgress from 'nprogress'
Now, you need to add some router events to control the behaviour of the progress bar.
In the pages/_app.js, add the following code:
Router.events.on('routeChangeStart', () => NProgress.start())
Router.events.on('routeChangeComplete', () => NProgress.done())
Router.events.on('routeChangeError', () => NProgress.done())
Depending upon your use case, you can remove the default loading spinner.
NProgress.configure({ showSpinner: false })
The final code for pages/_app.js will look like this:
import Router from 'next/router'
import NProgress from 'nprogress'
Router.events.on('routeChangeStart', () => NProgress.start())
Router.events.on('routeChangeComplete', () => NProgress.done())
Router.events.on('routeChangeError', () => NProgress.done())
NProgress.configure({ showSpinner: false })
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Results
At this point, you are done with the code and the final step is to test your app.
Go to your Next.js app and navigate to a new route. Your progress bar will be displayed like this: