Creating paths on-the-fly from GraphQL API within Nextjs

Having trouble accessing individual project pages from my project list. Keep encountering a 404 error page instead.

I've attempted to retrieve the data using both simple Fetch and ApolloClient, but the bug persists.

Error messages like 'could not load scripts from page [].js' pop up occasionally.

This is the directory structure of the pages

https://i.sstatic.net/6LvNk.png

Here is my code snippet for the getStaticProps and getStaticPaths functions:

export async function getStaticProps({ params }) {
    const { projectId } = params

    const result = await fetch(
        `${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/graphql`,
        {
            method: 'POST',
            headers: {
                // Authorization: `Bearer`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                query: `
                     query GetProject($path: String!) {
                        nodeArticles(where: {path: $path},limit: 1) {
                            nodes {
                                title
                                body {
                                    value:processed
                                }
                                image {
                                    url
                                }
                                path
                            }
                        }
                    }
                `,
                variables: {
                    path: projectId,
                },
            }),
        },
    );

    if (!result.ok) {
        console.error(result);
        return {};
    }

    const { data } = await result.json();

    const [ProjectData] = data.nodeArticles.nodes;

    return {
        props: { data: ProjectData || null },
    };

}
export async function getStaticPaths() {
    const result = await fetch(
        `${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/graphql`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                query: `
                    {
                    nodeArticles(first: 100) {
                        nodes {
                                path
                            }
                        }
                    }
                `,
            }),
        },
    );

    if (!result.ok) {
        console.error(result);
        return {};
    }
    const { data } = await result.json();

    const projects = data.nodeArticles.nodes;

    const pagesPaths = projects.map(({ path }) => {
        return {
            params: { projectId: path },
        };
    });


    return {
        paths: pagesPaths || [],
        fallback: false,
    };
}

Answer №1

When working with next.js, it is important to keep your pages in the 'page' directory. Check out this link for more information.

You may still encounter some issues in your code, but presentation is key

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

Eliminate the loading screen in Ionic 2

Within my app, there is a button that triggers the opening of WhatsApp and sends a sound. Attached to this button is a method that creates an Ionic loading component when clicked. The issue I am facing lies with the "loading.dismiss()" function. I want the ...

Leveraging Vue mixin within a @Component

After implementing the vue-property-decorator package, I encountered an issue when trying to use a mixin method inside the beforeRouteEnter hook. Here is what I initially tried: import { Component, Mixins } from 'vue-property-decorator'; import ...

I have chosen Next.js for my frontend development, while our backend developer is crafting the API in Express and MySQL. I am looking for ways to secure and protect the

As a beginner frontend developer learning Next.js, I've been tasked with integrating authentication into our app. The backend developer is working on creating the API using Express and MySQL. After successful login, an accessToken is received. However ...

When utilizing RxJS, the process of filtering Observable data may not function as expected if the filtering is carried out within a separate function rather than directly within the subscribe

While attempting to filter data from an external source using the RxJS filter on Observables, I encountered an issue where all records were returned instead of just the ones meeting the filtering criteria. This problem occurred when the code was within a l ...

When using NextJS with next-i18next and Firebase functions, all pages are redirected to a 404 error page if the locale is included

I have implemented next-i18next with Next.js in a setup that involves SSR deployed to Firebase functions. I followed the guidelines provided in this documentation https://github.com/i18next/next-i18next During development, everything functions correctly, ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

Unable to construct a node typescript project using solely production dependencies

I am currently working on a Node TypeScript project that utilizes various third-party libraries such as express. To ensure type safety, I typically install the @types/express module as a dev dependency following common instructions. The installation works ...

Angular Unordered Query Exploration

I'm currently working on implementing a search feature in my code where I want to filter elements of a list based on user input. The filtering works well if I search for the elements in a specific order. For example, if I search for 'red blue yel ...

What is the operator to conditionally chain Observables together?

My goal is to extract paginated data from a REST API and integrate it into my Angular application. The structure of the data sent by the API typically looks like this: { "next": null, "results": [ {"id": 7, "name": "Alicia"}, {"id" ...

Unfortunately, Suspense is not yet supported by ReactDOMServer in NextJS

Currently, I'm in the process of integrating a loader component into a NextJS website. My goal is to utilize Suspense to display a loading screen when the page is refreshed or routes are changed. Here is the code snippet: import Head from 'next/h ...

Utilizing Typescript: Ensuring an array includes only specified values from an enum through strict enforcement

In my Angular application, I have an HTTP service that returns the allowed accesses for a specific user. The response structure is as shown below:- { "accessId": 4209318492034, "folderPath": "data/sample_folder/", ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

Explore the capabilities of the Angular Ng2SearchPipeModule to enhance your search input

I used the ng2SearchPipeModule for an input search, but it's not working. I can't seem to find my error. In my HTML, all my books are within divs. Will typing a book title display all the divs? Of course, I have imported in app.module.ts Ng2Sear ...

Typescript throwing an exception for a properly defined parameter

Using a combination of NextJs and typescript, I am encountering an issue when passing a correctly typed prop. The error that is displayed is as follows: ./pages/jobs.tsx:100:15 Type error: Type '{ job: jobType; key: number; handleTagClick: (tag: strin ...

Tips for evaluating the stickiness of a block within a cell when it adheres to a mat-header-cell

I am working with an Angular table and facing an issue. How can I make the span element in the cells of the first column stick to the sticky mat-header-row when scrolling down the table? My requirement is for the span element to stay attached to the lower ...

Deploying a blank page with GraphQL on Heroku

I've been attempting to deploy a GraphQL API from this repository: https://github.com/DimiMikadze/create-social-network, but I'm encountering some issues and the page remains blank. The frontend has been deployed on Netlify. It functions fine in ...

Error encountered while importing DataTables.Settings in Angular with DataTables

Attempting to utilize DataTables with Angular for data visualization within my application has been a challenge. After installing DataTables using ng add angular-datatables and importing the DataTablesModule in the app.module.ts, I encountered an issue whi ...

Creating a custom event handler for form input changes using React hooks

A unique React hook was created specifically for managing form elements. This hook provides access to the current state of form fields and a factory for generating change handlers. While it works seamlessly with text inputs, there is a need to modify the c ...

Implement the anti-flickering script for Google Optimize in a NextJS/ReactJS environment

While working on a NextJS/ReactJS project, I am experimenting with setting up Google Optimize for some tests. One issue I have encountered is the flickering effect that occurs when Optimize changes visual elements during experiments. To address this probl ...