4 min

September 9, 2024

Easy Ways to Handle 404 pages from Storyblok with Nuxtjs

When building a website, ensuring a seamless user experience is crucial. However, there are times when a user might navigate to a page that doesn't exist, resulting in a "404 Not Found" error. While this is a common issue, the way you handle 404 error pages can significantly impact the user experience. In this blog post, we’ll explore how to handle 404 error pages in a Nuxt.js project integrated with Storyblok as the headless CMS.

Listen to the audio version of this article.

elevenlabs cover
Loading the Elevenlabs Text to Speech AudioNative Player...

Why Customize 404 Error Pages?

A generic 404 error page can be a dead-end for users, leading to frustration and potential loss of engagement. By customizing this page, you can:

  • Maintain brand consistency.

  • Provide useful information and navigation options.

  • Engage users and guide them back to relevant content.

The problem

Storyblok doesn't have clear guidelines in documentation on how to handle 404 pages. Moreover, there is no dedicated endpoint for it in Content Delivery API V2. The only way to know if story exists is to try to fetch it.

Option A (handle errors directly on the page)

Trigger context.error everywhere we fetch data for pages if we catch an error. It will be looking something like this

The problem with this solution as we have to copy paste this code in many places in our codebase. Another reason not to use this option is because we see the page layout for a moment before being redirected to 404 page. To resolve this issue we can use middleware.

Option B (middleware + pinia)

Create middleware to handle storyblok fetching and save the result to global store. We will be using pinia store.

stores/storyblok.ts

middleware/story-url-resolver.ts

This solution seems to be working, but now we face a known bug in Nuxtjs v2 mentioned here.

In general, the issue was that at the time of parallel opening of the page (on any device), the application context was shared and page B had in the SSR data of page A which resulted in an error in rendering the content of the page.

Option C (middleware + context)

Now we're not gonna be using pinia store, we're going to save story directly into middleware's context instead.

We need to make small adjustments in our pages components to use asyncData in order to get data from context on client and on the server