How to access Netlify's read-only vars with next.js site?

We’re deploying a Next.JS site that have a form using POST method to reach Next’s API and then send data to Notion’s databases. The fetch() function will use the current url summed to that api functions path to work, but it seems the native env vars for Netlify aren’t working.

// url to send the form data to
  const sanitizedFormType = _.lowerCase(formType)
  const sanitizedFormTitle = _.startCase(formTitle)
  const siteUrl = process.env.NODE_ENV === 'production' ? "env var for current url" : 'http://localhost:3000'
  const urlPath = siteUrl + `/api/${sanitizedFormType}/` + sanitizedFormTitle
  // console.log('urlPath', urlPath)

  const submitForm = async (values) => {
    const res = await fetch(urlPath, {
      // this is the url with the appendage of the form title
      method: 'POST', // this is the method to use when sending the data
      body: JSON.stringify(values, null, 2), // this is the data to send. have tried shaping the object with no success. this works better
      headers: {
        'Content-Type': 'application/json'
      }
(...)

The string for production is just a placeholder. I’ve tried DEPLOY_PRIME_URL for previewing the site and the form won’t work because it returns undefined.

I’ve red this post and tried to implement this technique using netlify.toml to print the vars for production and previewing into a .env.local but it seems to work only for my localhost, is that correct?

So, how do we work with such cases using Next.JS in Netlify? Is there an way to pull vars based on context or to insert branch based vars into enviroment at deploy settings for this site?

The project is landing-origem.netlify.app.

Hi @Eduoliveira,

I don’t believe there’s an easy solution to do this, except to write a build plugin which would read the build-time variable like the one you tried to access and inject that inside your Functions.

I understand. Would this plugin apply to my case?

netlify-plugin-inline-functions-env

The description makes it seem so - but I haven’t used it personally, so can’t say.