Using getStaticProps in Next.js to retrieve menu data and seamlessly integrate it into the layout

I have integrated Sanity.io as a backend for my project, specifically managing the data for my main menu in parent/children object arrays.

While I am able to successfully fetch this data, I prefer to utilize getStaticProps to ensure that my site remains completely statically generated.

Unfortunately, getStaticProps does not work in my layout.js file since it is not located in the "pages" directory. The same goes for the _app.js file.

Therefore, I currently fetch the menu data within each page and pass it as a prop into the Layout component (which now needs to be on every page) so that I can then pass it from the Layout into the header component. Here's how my page structure looks:

function Page({ menu }) {
  return (
    <Layout menu={menu}>
      <article>
         ...
      </article>
    </Layout>
  )
}

export const getStaticProps = async (context) => {
  const menu = await client.fetch(**menu query**);

  return {
    props: {
      menu,
    },
  };
}

I understand that the Layout component should ideally be placed inside the _app.js file, but unfortunately, this is not possible at the moment.

Despite being aware of the complicated process involved, using getInitialProps within Layout seems to be the only other option, though it would mean resorting to SSR rather than SSG.

After extensive research, the most promising response I found was that incorporating getStaticProps in the layout "will be allowed in the near future." However, this statement was made some time ago...

If anyone can provide guidance or direction on how to handle this issue more efficiently, it would be greatly appreciated. It feels unnecessary to include the layout on every single page solely to pass data into the header component during build time.

Answer №1

Even though I am still searching for a more efficient solution that doesn't require fetching menu data in getStaticProps on every page and passing it up to Layout -> Header, I recently stumbled upon an interesting Node-based approach shared by Brewhouse digital. You can check out the guide titled NextJS getStaticProps With Components, which offers a cool alternative.

The concept involves creating a "pre-build" process that runs before the build starts. This process fetches the necessary data from your endpoint and saves it locally as a JSON file. Then, you can simply read this JSON file directly into components like Layout or Header.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The problem with THREE JS OcclusionComposer: encountering "Cannot read properties of undefined (reading 'x')" error

I am attempting to replicate the Volumetric Lighting demonstration created by JMSWRNR but I am encountering difficulties with the Occlusion Composer. Since I am not well-versed in GLSL, debugging has proven to be quite challenging, especially for someone l ...

Utilize the dropdown menu to load JSON data and dynamically update the content of a div section on a website

I have been struggling to find a way to load JSON data from a drop down menu into a div area and refresh it with new results. While I was able to display the data in the div area without the dropdown menu, I am facing difficulty in fetching the required da ...

Vue components are failing to appear in the live environment, however they function perfectly in the development environment

My Laravel Vue project runs smoothly in development, but on the live shared hosting server, the vue components are not displaying. However, the Laravel views function correctly with no errors in the console. I have already run npm run production to minif ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration: $routeProvider .when('/person/:person_id', { controller: 'person', templateUrl: 'partials/person.html', resolve: { data: ['api', '$route', ...

Animating a JQuery Slider using code from scratch

I'm attempting to dynamically alter/animate a JQuery slider. In this scenario, there are two arrays present: one for the values that need to be modified and another for the durations between modifications. By monitoring the console, you'll observ ...

I encountered an issue while attempting to manipulate/retrieve the JSON value using REGEX, resulting in an undefined return

I am attempting to retrieve the currency value from a JSON file and if it is USD, then I want to change it to AUD. When trying to find the currency attribute in the JSON file, it returned 'undefined' as shown below: Code: var datastring = JSON. ...

Ensure that all links are opened in a new tab

When including _blank in the a href URL, my website contains various elements like iframes and ads from Adsense, Taboola,, etc. Currently, when a user clicks on an iframe or ad, it opens in the same window. Is there a way to ensure that all URLs (includin ...

What is the quickest way to redirect a URL in WordPress?

Is it possible to redirect a URL instantly in WordPress using this script code? JavaScript Code: jQuery(document).ready(function() { var x = window.location.href; if (x == 'http://example.com/') { window.location.hr ...

Is there a way to update Checkbox changes within a Datagrid without selecting the entire row?

My Table Cell Checkbox Behavior Issue: Within a table cell, I have a checkbox that changes upon clicking it. However, the change only occurs the first time. Subsequent clicks on the same checkbox do not trigger any change until I click outside the cell. T ...

How can I add page transitions to my simple HTML website?

Working on an internal website project for my office using vue.js has been a rewarding experience. I appreciate how easily it allows me to manage multiple pages with dynamic content and seamless transitions. Unfortunately, my IT department is hesitating to ...

Troubleshooting: Issues with JQuery validation for cross-domain URLs

I'm fairly new to using JQuery and I have a specific requirement which involves validating a link from another domain. If the validation is successful, I need to redirect (open the page in a new window) to that link. Otherwise, I should display an ale ...

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

Detecting when an object exits the proximity of another object in ThreeJS

In my ThreeJS project, I have planes (Object3D) flying inside a sphere (Mesh). My goal is to detect when a plane collides with the border of the sphere so that I can remove it and respawn it in a different location within the sphere. I am wondering how I ...

Splitting data in NodeJS sockets

Whenever I encounter the need to divide data, my standard practice involves converting it into a string format. Here's an example of how I handle data in my function: socket.on('data', function (data) { var str = data.toString().spl ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

What causes the duplication of my data when using server-side data fetching with Next.js and @apollo/client?

I am currently working on a project using nextjs and @apollo/client. The data for my project is fetched from an external API. However, I have encountered an issue where when I navigate to a different page and then go back to the previous page, the data is ...

When trying to pass props from a parent to a component in Next.js, the issue of props

Within /pages/profile.js, I am utilizing the LovedOne element by passing values from props. Upon debugging, it is evident that these values are indeed valid when passed. import React from "react"; import LovedOne from "../components/loved_on ...

Check to see if the upcoming birthday falls within the next week

I'm trying to decide whether or not to display a tag for an upcoming birthday using this boolean logic, but I'm a bit confused. const birthDayDate = new Date('1997-09-20'); const now = new Date(); const today = new Date(now.getFullYear( ...