skip to Main Content

I am trying to build a dynamic page with using WordPress as the data source.

I am not getting getStaticProps and getStaticPaths correct and it is causing errors

Error: The provided path `/` does not match the page: `/[slug]`.

I have hard coded the page name now for testing purposes (ideally I would like to make it dynamic) (I have tried making codesandbox for this, but I always seem to have trouble with next.js and codesandbox).

I navigate to http://localhost:3000/art-shows to test

this is my [slug].js page

import Head from 'next/head'
import Link from 'next/link'
import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
import { CMS_NAME } from '../lib/constants'
import Header from '../components/header'



export default function Index() {

console.log(router.query)
  return (
    <>
      <Layout>
        <Head>
          <title>page</title>
        </Head>
       <Header />
        <Container>
         Hello World
          
        </Container>
      </Layout>
    </>
  )
}


export async function getStaticProps({ params }) {
    
    
  const data = await getAllPagesBySlug('/art-shows')

  return {
    props: {
      page: data.page,
  
    },
  }
}

export async function getStaticPaths() {
  const allPages = await getAllPagesWithSlug()

  return {
    paths: allPages.edges.map(({ node }) => `${node.uri}`) || [],
    fallback: true,
  }
}

this is my connection ../lib/api’

const API_URL = process.env.WORDPRESS_API_URL

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' }

  if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
    headers[
      'Authorization'
    ] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
  }

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query,
      variables,
    }),
  })

  const json = await res.json()
  if (json.errors) {
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  }
  return json.data
}


  
export async function getAllPagesBySlug($id) {
  const data = await fetchAPI(`
    {
     
        page(id: $id, idType: URI) {
            content
            isFrontPage
            isPostsPage
            uri
            title(format: RAW)
            seo {
              title
              metaDesc
              metaRobotsNofollow
              metaRobotsNoindex
            }
            featuredImage {
              node {
                sourceUrl
              }
            }
          }
    }
  `)
  return data
}


export async function getAllPagesWithSlug() {
  const data = await fetchAPI(`
    {
      pages(first: 10000) {
        edges {
          node {
            uri
          }
        }
      }
    }
  `)
  return data?.pages
}

  
  

2

Answers


  1. Chosen as BEST ANSWER

    Thanks again. I had put all the blog into its own folder, I left pages in the root folder. I finally got it working as so.

    [slug.js] many changes

    import Head from 'next/head'
    import Link from 'next/link'
    import Container from '../components/container'
    import MoreStories from '../components/more-stories'
    import HeroPost from '../components/hero-post'
    import Intro from '../components/intro'
    import Layout from '../components/layout'
    import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
    import { CMS_NAME } from '../lib/constants'
    import Header from '../components/header'
    
    
    
    export default function Page( {page} ) {
    
    
      return (
        <>
          <Layout>
            <Head>
              <title></title>
            </Head>
           <Header />
            <Container>
            <div dangerouslySetInnerHTML={{ __html: page.content }} />
            
              
            </Container>
          </Layout>
        </>
      )
    }
    
    
    
    
    export async function getStaticProps({ params }) {
        
      const data = await getAllPagesBySlug(params.slug)
      console.log(data)
      
      
      return {
        props: {
          page: data.page,
      
        },
      }
    }
    
    
    
    
    export async function getStaticPaths() {
      const allPages = await getAllPagesWithSlug()
    
      return {
         
         //paths:  [ { params: { slug: '${node.uri}' } }  ],
        paths: allPages.edges.map(({ node }) => `/${node.slug}`) || [],
        fallback: true,
      }
    }
    

    and query modifications (page(id: "${$id}", idType: URI) {)

    export async function getAllPagesBySlug($id) {
      const data = await fetchAPI(`
        {
         
            page(id: "${$id}", idType: URI) {
                content
                isFrontPage
                isPostsPage
                uri
                content
                title(format: RAW)
                featuredImage {
                  node {
                    sourceUrl
                  }
                }
              }
        }
      `)
      return data
    }
    

  2. If you want to get all slugs, then your file should be named […slug].js (Note the … spread operator) then inside of the file use the useRouter() hook and extract an array of slugs like this:

     const router = useRouter();
     const slug   = router.query.slug || [];
    

    Example: https://codesandbox.io/s/twilight-darkness-ktpd2?file=/pages/%5B…slug%5D.js

    If you fork the sandbox link above then you will have a nextjs template to use code codesandbox. If the above doesn’t work, fork the sandbox and put your code in and let me know so I can look it over.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search