Search code examples
next.jscorsprismic.io

NextJs Fetch Data from Prismic blocked by CORS


I want to fetch and display lists of my content on simple blog. But when I run the code, it always says that my request has been blocked by a CORS.

I'm even lost because I just want to see the data displayed.

This is my code.

import { createClient } from '../../../prismicio'
import React, { useEffect, useState } from 'react'

export default function Page() {
  const [page, setPage] = useState(null)

  useEffect(() => {
    const fetchData = async () => {
      const client = createClient()
      const uid = 'my-first-post' // Replace with your desired UID

      try {
        const response = await client.getByUID('blog_content', uid)
        setPage(response)
        console.log(response)
      } catch (error) {
        console.error('Error fetching data:', error)
      }
    }

    fetchData()
  }, [])

  return (
    <div className="mt-40">
      {page ? <h1>Page is fetched.</h1> : <p>Loading...</p>}
    </div>
  )
}

I think the code is correct, but when I check my console, it says..

from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Can anyone please help? Ask me questions and I'll respond to it.


Solution

  • Next.js recommends fetching data from a CMS like Prismic using getStaticProps().

    Assuming you are using the Pages Router, you can move your Prismic query into a getStaticProps() function. The return value of that function determines the props provided to your page component, which can be used to render your content.

    Data fetched on the server (i.e. Node.js) is not subject to CORS.

    import { createClient } from "@/prismicio";
    
    export default function Page({ page }) {
      return (
        <div className="mt-40">
          {/* Do something with the `page` prop. */}
        </div>
      );
    }
    
    export async function getStaticProps({ params, previewData }) {
      const client = createClient({ previewData });
    
      const page = await client.getByUID("blog_content", params.uid);
    
      return {
        props: { page },
      };
    }