Next.js SSR + API route with site protection enabled

I was puzzling over a strange 500 error that only occurred in a deployed Netlify site that was using Next.js SSR. It fetches data from an API route before rendering the page. I eventually thought to curl the API route and realized that site protection was preventing it from returning data (it returns the Netlify password page) and causing a 500 error. I assume this is what’s happening when my SSR function tries to fetch the data, since as soon as I disabled password protection, the page worked as expected.

Is there any way I can enable site protection but allow the SSR function to authenticate when it tries to fetch from the API route? Thanks.

Is the site that’s fetching the data, displaying the data and has the password same? I don’t understand your setup from the description. Mind sharing the site?

Hi,

I ran into this exact issue today for my site.

The issue is that we’re trying to call the API for the site during build. Since the site is password protected it will fail since the API call will return 401.

Is there any way to pass the password along with the API call to allow us to use the site API while still having the site being password protected?

I’m still confused and you did not provide a site either. Are you both accessing the same site during the build on which you’ve the API? Won’t that mean you’re accessing a previous version of the API? In any case, password can be used as the following:

import axios from 'axios'
const data = new FormData()
data.append('form-name', 'form 1')
data.append('password', 'your password')
const url = 'https://deploy-preview-209--fastidious-gelato-96b6a2.netlify.app/'
axios({
  data: new URLSearchParams(data).toString(),
  maxRedirects: 0,
  method: 'post',
  url,
  validateStatus: status => {
    return status === 302
  }
}).then(passwordResponse => { 
  axios({
    headers: {
      cookie: passwordResponse.headers['set-cookie'][0].split(';')[0]
    },
    responseType: 'text',
    url
  }).then(siteResponse => {
    console.log(siteResponse.data)
  }, siteResponseError => {
    console.log('Error in second call: ', siteResponseError)
  })
}, passwordResponseError => {
  console.log('Error in first call: ', passwordResponseError)
})

This is an axios example, but you can definitely convert it to fetch or anything else.

We’re just stating an obvious issue that wasn’t documented, no need to provide a site url for that in my opinion. For my use case it doesn’t matter if the version of the API is of the previous build.

Thanks for your example, I’ll try it later during the week.