npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nuxt-page-dependencies

v1.1.0

Published

Defer rendering of components that depend on page data during SSR

Downloads

393

Readme

nuxt-page-dependencies

Defer rendering of components that depend on page data during SSR

This Nuxt 3 module implements a way to defer rendering of components (think breadcrumbs, language links) outside of the tree of a page component until page rendering is done.

The obvious solution would be to put all components that depend on page data into the page component itself. But this would render them on every route change, which is most likely not what we want.

Setup

npm install --save nuxt-page-dependencies
export default defineNuxtConfig({
  modules: ['nuxt-page-dependencies'],
})

The module only has a single option called checkComposableCalled. If set to true (default), it will check the contents of all page components to make sure the composable is called.

Usage

Wrap components that need page data

<template>
  <NuxtPageDependency>
    <Breadcrumb />
  </NuxtPageDependency>
</template>

Call composable to start rendering dependencies

// Do stuff that mutates global state.

// Render <Breadcrumb>.
await renderPageDependencies()

// Done!

The problem

Let's say you have a layout component in layouts/default.vue:

<template>
  <div class="default-layout">
    <Navbar />
    <Breadcrumb />
    <div>
      <slot></slot>
    </div>
  </div>
</template>

And this component that renders the current breadcrumb:

<template>
  <ul class="breadcrumb">
    <li v-for="(link, i) in breadcrumbs" :key="i">
      <NuxtLink :to="link.url">{{ link.label }}</NuxtLink>
    </li>
  </ul>
</template>

<script setup lang="ts">
const { breadcrumbs } = useBreadcrumb()
</script>

And a page component like this:

<template>
  <div>
    <h1>{{ page?.title }}</h1>
  </div>
</template>

<script setup lang="ts">
const route = useRoute()
const { setBreadcrumbs } = useBreadcrumb()

const { data: page } = await useAsyncData(() => {
  return $fetch('/api/get-page', {
    query: {
      path: route.path,
    },
  })
})

setBreadcrumbs(page.value.breadcrumb)
</script>

This results in the following component tree (simplified):

- <App>
  - <Layout>
    - <Navbar>
    - <Breadcrumb>
    - <NuxtPage>
      - <YourPageComponent>

By default, the <Breadcrumb> component will display no breadcrumb, due to breadcrumbs being empty. This is because the page component did not yet render.

The solution

The module provides a component called <NuxtPageDependency> that can be used to wrap other components or parts of a template. It will only start rendering its default slot once the page has finished rendering:

<template>
  <NuxtPageDependency>
    <ul class="breadcrumb">
      <li v-for="(link, i) in breadcrumbs" :key="i">
        <NuxtLink :to="link.url">{{ link.label }}</NuxtLink>
      </li>
    </ul>
  </NuxtPageDependency>
</template>

<script setup lang="ts">
const { breadcrumbs } = useBreadcrumb()
</script>

This also works for any part of a template, as can be seen in the example above.

Under the hood, the component returns a Promise in its setup() method and waits for a specific event to be emitted. This event must always be emitted manually, using the renderPageDependencies() composable:

<template>
  <div>
    <h1>{{ page?.title }}</h1>
  </div>
</template>

<script setup lang="ts">
const route = useRoute()
const { setBreadcrumbs } = useBreadcrumb()

const { data: page } = await useAsyncData(() => {
  return $fetch('/api/get-page', {
    query: {
      path: route.path,
    },
  })
})

// First update the state.
setBreadcrumbs(page.value.breadcrumb)

// Render the dependent components.
await renderPageDependencies()
</script>

Custom composables

For the checkComposableCalled option you may also provide an array of composable names to check, for example if you create your own composable that fetches page data and sets global state and calls renderPageDependencies.

export default defineNuxtConfig({
  modules: ['nuxt-page-dependencies'],
  pageDependencies: {
    checkComposableCalled: ['renderPageDependencies', 'loadPageData'],
  },
})
export async function loadPageData(): Promise<PageData> {
  const route = useRoute()
  const data = await useFetch('/api/load-page-data', {
    query: {
      id: route.params.id,
    },
  })

  setBreadcrumbs(data.breadcrumbs)

  // Call the composable so that <NuxtPageDependency> components can be rendered.
  await renderPageDependencies()
}
<template>
  <div>
    <h1>{{ page?.title }}</h1>
  </div>
</template>

<script setup lang="ts">
const page = await loadPageData()
</script>

The now introduced problem

Obviously, this is more of a workaround than a proper solution. It's also dangerous: If you forget to call the renderPageDependencies() composable in a page component, you will completely block SSR, because the Promise is never resolved. While the <NuxtPageDependency> component does resolve the Promise when there is already an error or when an error happens, it does not implement a setTimeout() or any other mechanism to resolve the Promise. Make sure to not forget calling the composable on every page!