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 value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Guide on creating a sitemap using Express.js

I've been working with the sitemap.js package from https://www.npmjs.org/package/sitemap While I can add URLs to the sitemap manually, my challenge lies in adding URLs based on data retrieved from MongoDB. Since fetching data from MongoDB is asynchro ...

Obtain a nested array of objects from Mongoose's Model.find() method and then make modifications to the inner array

I need to retrieve an array of objects with a specific ID from my database within a server route, and then update a property of an object within that array (rather than returning just the objectID, I want to return the Document as an object with the specif ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...

Having trouble retrieving react environment variables from process.env?

When developing my React App, I utilized a .env file to securely store some essential API keys. However, as I attempted to access these variables using process.env, I encountered an issue where the values appeared to be set as undefined. To launch the app ...

The process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

Using jQuery to Decode the XML Document Containing National Threat Level Data

Recently, I've been experimenting with using jQuery to extract data from the DHS Threat Level found in their XML file. However, despite my efforts, I haven't been able to make it work. As a newcomer to Javascript and non-presentational jQuery, I& ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...

What is the best way to implement a personalized hook in React that will return the number of times a specific key is pressed?

I'm working on a custom hook that should give me the key pressed, but I've noticed that when I press the same key more than twice, it only registers twice. Here's my code: import { useEffect, useState } from "react" function useKe ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

Sveltejs template not displaying on M1 MacBook Air after running - stuck on blank screen

Currently, I am in the process of learning Sveltejs and have been utilizing for the tutorial, which has been quite effective. However, I decided to work on developing and testing Sveltejs applications locally on my MacBook Air M1. I downloaded the provid ...

Bring in TypeScript property from an external scope into the current scope

I am encountering an issue with my TypeScript code. Inside the anonymous functions, I am unable to change the properties of the class because they are out of scope. Is there a way to pass them in so that they can be modified? class PositionCtrl { ...

Determining the maximum number within an array using JavaScript

Similar Question: How can I identify the largest number in a JavaScript array? I'm facing issues with this piece of code. Despite spending some time on it, I can't seem to make it work properly. The console only shows 0 when I run it. Can som ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

What is the reason for next.js to execute getStaticPaths each time a page is loaded?

During the pre-rendering of my product detail pages, I encountered an issue with Next.js where the getStaticPaths function was being called on every page refresh or URL change even if it was the same page. This caused a delay and made the page unresponsive ...

Observables in Knockout.js vanish after being bound

I'm encountering a peculiar issue with my Knockout script. Here is the viewModel: viewModel = { viewShown: function () { if (params.id !== undefined) timer = setInterval(loadVorgangsdetails, 100); else { $( ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

Is it possible for Response.Redirect and OnBeforeUnload to cooperate effectively?

Is there a way to detect if the server-side code has sent a Response.Redirect in an OnBeforeUnload event? I need to alert the user before they navigate away from a page, but I don't want the prompt to appear when the server redirects. I'm dealin ...

Adjusting the Connection header in a jQuery ajax request

I've been attempting to modify the Connection header using the code below, but so far, I haven't had any success jQuery.ajax({ url: URL, async: boolVariable, beforeSend: function(xhr) { xhr.setRequestHeader("Connection ...