DEV Community

Cover image for Replacing NProgress in Vue 3 and Nuxt
Navid jaberi
Navid jaberi

Posted on Edited on

Replacing NProgress in Vue 3 and Nuxt

NProgress gets almost 5 million downloads a week. Its last release, 0.2.0, came out in May 2015, and it doesn't ship TypeScript types, so another 1.5 million downloads a week go to @types/nprogress. It still works, and in a Vue 3 app it usually looks like this:

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

router.beforeEach(() => { NProgress.start() })
router.afterEach(() => { NProgress.done() })
Enter fullscreen mode Exit fullscreen mode

That setup has two problems you've probably seen without naming them.

Problem 1: it flashes on fast navigations

start() shows the bar right away. When the next route is already loaded, or its data comes from cache, the navigation takes 30ms and the user sees a thin line blink at the top of the page. That blink makes a fast app look slow.

Problem 2: parallel requests end it too early

People also call NProgress around their own requests:

async function load(url: string) {
  NProgress.start()
  try { return await fetch(url).then((r) => r.json()) }
  finally { NProgress.done() }
}

await Promise.all([load('/api/user'), load('/api/orders')])
Enter fullscreen mode Exit fullscreen mode

NProgress holds one state, not a count. The second start() finds the bar already running and counts nothing. When /api/user comes back first, its done() finishes the bar, while /api/orders is still loading. The page looks ready, and then the orders pop in.

The fix, if you want to keep NProgress

You need two numbers: a delay before the bar appears, and a count of running tasks. About 20 lines:

// progress.ts
import NProgress from 'nprogress'

const DELAY = 200
let pending = 0
let timer: ReturnType<typeof setTimeout> | undefined

export function start() {
  pending++
  if (pending === 1) timer = setTimeout(() => NProgress.start(), DELAY)
}

export function done() {
  if (pending === 0) return
  pending--
  if (pending === 0) {
    clearTimeout(timer)
    NProgress.done()
  }
}
Enter fullscreen mode Exit fullscreen mode

A task shorter than 200ms clears the timer before the bar ever shows, and the bar stays up until the last task calls done().

Wire the router through the same counter, and make sure a navigation holds one slot at most. A redirect runs beforeEach a second time for the same navigation, but afterEach runs once:

let navigating = false
const begin = () => { if (!navigating) { navigating = true; start() } }
const end = () => { if (navigating) { navigating = false; done() } }

router.beforeEach(begin)
router.afterEach(end) // also runs for aborted and duplicated navigations
router.onError(end)   // a guard or a lazy route threw
Enter fullscreen mode Exit fullscreen mode

That navigating flag matters: without it, a redirect counts twice, and the bar never finishes.

Or replace it

I needed the same thing in a Vue 3 library I maintain, so it has a component for it: <PageProgress> in vue-smart-loading-kit. It does what the snippets above do, with no NProgress underneath:

// main.ts
import VueSmartLoadingKit from 'vue-smart-loading-kit'
import 'vue-smart-loading-kit/style.css'

app.use(VueSmartLoadingKit, { router })
Enter fullscreen mode Exit fullscreen mode
<!-- App.vue -->
<PageProgress color="#7c3aed" />
<RouterView />
Enter fullscreen mode Exit fullscreen mode

For your own requests:

import { usePageProgress } from 'vue-smart-loading-kit'

const progress = usePageProgress()
progress.start()
await saveSettings()
progress.done()
Enter fullscreen mode Exit fullscreen mode
  • A task shorter than delay (200ms by default) never shows the bar.
  • Tasks are counted, so the bar stays until the last one is done.
  • A redirected navigation counts once and only ends its own slot. It never ends a task you started by hand.
  • The bar eases toward 90%, because the real duration is unknown, and done() runs it to 100% before it fades out.
  • It's typed, and vue-router isn't a dependency. It only calls beforeEach, afterEach and onError.
  • It's safe with SSR. Each app gets its own counter, so two requests on the server never share one.

Moving over

NProgress PageProgress
NProgress.start() usePageProgress().start()
NProgress.done() usePageProgress().done()
router hooks in main.ts app.use(VueSmartLoadingKit, { router })
import 'nprogress/nprogress.css' import 'vue-smart-loading-kit/style.css'
color in your own CSS color prop, or pageProgress.color in the plugin options
NProgress.configure({ showSpinner: false }) nothing to do, it has no spinner
NProgress.set(0.4), NProgress.inc() no equivalent: use <ProgressBar :value="40"> when you know the real percentage

In Nuxt

Nuxt already ships <NuxtLoadingIndicator>, and it waits 200ms before it shows (its throttle option), so it doesn't flash. If you only need a bar for page navigation, keep it.

It tracks one loading flag, though. useLoadingIndicator() gives you start() and finish(), and the first finish() ends it, the same way NProgress does with parallel requests. If you want your own requests counted as well, the Nuxt module connects <PageProgress> to the router for you:

npx nuxi module add nuxt-smart-loading-kit
Enter fullscreen mode Exit fullscreen mode
<!-- app.vue -->
<PageProgress />
<NuxtPage />
Enter fullscreen mode Exit fullscreen mode

usePageProgress() is auto-imported. Use one bar or the other, not both.

Try it

The same library also has v-skeleton, which turns your real component into its own loading skeleton. I wrote about testing it on Vuetify and Nuxt UI last time.

Top comments (0)