DEV Community

Use NProgress with Next.js (Router and fetch events)

Vincent on June 09, 2020

Today I was trying to add NProgress https://github.com/rstacruz/nprogress to my Next.js project. I wanted the progress bar to: show when switchi...
Collapse
 
mxmzb profile image
Maxim

Nice, writeup. I instantly was reminded of doing this with Turbolinks in Rails back in the days.

Although it's technically a nice solution, I actually dislike the top progress bar on websites. Somehow, I always feel like I have to wait longer because of the progress bar. Maybe it's because only slow loading sites use it, and I am wrongly attributing it to the bar. 🤷‍♂️

Collapse
 
vvo profile image
Vincent

Yep indeed it can feel this way, when it's fast enough though and delayed then it's a good indicator that "the UI is up to date now"

Collapse
 
antchinchilla profile image
Anthony Ch

Hi, it works good with routing but it doesnt work with fetch, im using node-fetch, is this the issue? which fetch package are you using for this? thanks!

Collapse
 
vvo profile image
Vincent

Hi there, with the latest Next.js versions you do not even have to include any fetch polyfill, so you can remove any fetch package and it should just works

Collapse
 
supermin profile image
Anturin Durimov • Edited

Hi, I like the solution. But if you use SWR with fetch, then with each revalidation the progress bar will appear. Is there a way to turn it off for SWR revalidate fetches?

Collapse
 
vvo profile image
Vincent • Edited

Good question; I am experiencing the same as you because of using SWR. For now, I am fine with it, but you're right; there should be a way to disable it.

Ways to do this:

  • use a custom fetcher that calls window. fetch() with some specific (non-standard) params allowing you to identify the calls to fetch are from SWR
  • in your fetch monkey patch, find the URL path, and if it's "/api" then you could not show the progress

If you try one of those or find other ways, let me know!

Collapse
 
titungdup profile image
dhondup

Hi, Does NProgress also work for initial site load? Like a loader?

Collapse
 
titungdup profile image
dhondup

Also, for some reason, the code is not working after adding TopProgressBar in _app.js