👀 See Sanity in action: Watch product demo now →

Next.js - How to Get Data From Sanity Using SWR

16 replies
Last updated: Sep 9, 2021
I am trying to fetch data from Sanity through a dynamic route in Next.js using SWR.This is the error I get even though the
projectId
is present in my configs
Sep 9, 2021, 7:59 AM
what do you get if you
console.log(options)
on L9?
Sep 9, 2021, 7:59 AM
user Y
Sep 9, 2021, 8:02 AM
huh - yeah, hard to say what’s going on here without a bit more context. Do you have a reproducible case or a repo you could point me to?
Sep 9, 2021, 8:05 AM
Yes I do. Here is the PR I’m working on. The Homepage works fine. The issue comes when you navigate to dynamic pages with slugs.
Sep 9, 2021, 8:10 AM
Updated link
Sep 9, 2021, 8:12 AM
I suspect it tries to do a client-side fetch in the browser where it can’t access the env-variables. https://github.com/inezabonte/car-rental-site/blob/create-car-page/lib/sanity.js#L3-L8
Try using the
NEXT_PUBLIC_
naming convention to get them in bundled in and accessible on the client side. The
projectId
and
dataset
is considered public because they make up the endpoint URLs for your APIs anyways, https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser
Sep 9, 2021, 8:15 AM
No longer getting the projectId error but I get this CORS error when the request is made
Sep 9, 2021, 8:34 AM
yes, you need to add the domain to your CORS origins settings
sanity cors add <https://dasilva-cars>-*.<http://vercel.app|vercel.app>
should probably do it for the preview URLs. I don’t think you need to allow for authenticated requests in this case.
Sep 9, 2021, 8:48 AM
You can also set it up in sanity.io/manage
Sep 9, 2021, 8:48 AM
How comes it doesn’t block the homepage as well since it’s also getting data from Sanity
Sep 9, 2021, 8:52 AM
I’d guess it’s because the first render happens server side? Next.js can be a bit confusing because it switches between doing server and client-side requests on navigation
Sep 9, 2021, 9:00 AM
Adding the CORS setting fixed it. Thanks
Sep 9, 2021, 4:02 PM
I was able to add localhost to the cors. Adding the deployed one with wildcard seems to be an issue
Sep 9, 2021, 5:49 PM
Ok? What happens if you try?
Sep 9, 2021, 5:53 PM
I’m not able to add the URL it gives me this error. I’ve also tried the urls from the docs example they have the same issue when wildcard is added
Sep 9, 2021, 5:56 PM
It works now. Issue was coming from Firefox. I refreshed the browser and was able to add it
Sep 9, 2021, 5:59 PM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in