Next.js Discord

Discord Forum

AxiosInstance with auth

Answered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
currently i have an axios instance like below. this works well with GET requests since i get the data in getServerSideProps. however, it will fail for POST because it is triggered in NextPage (because it is in client side so those env vars are unavailable ). so my question is - how to make it work without putting them to NEXT_PUBLIC_ / publicRuntimeConfig since they are secrets.

const instance: AxiosInstance = axios.create({
  baseURL: process.env.API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  auth: {
    username: process.env.API_AUTH_USERNAME,
    password: process.env.API_AUTH_PASSWORD,
  },
})
Answered by Ray
I would create a router handler or use server action so you could use the axios instance without exposing those secret.
View full answer

9 Replies

Answer
Sloth bearOP
thanks for the direction. I'll research a bit n give it a try.
Sloth bearOP
does both of the ways require app folder n min next 13?
are you using page router? if so, you could use api route
Sloth bearOP
yes. currently i havent migrated to app layout as there s lots of efforts.
if i use api route, then i can still use the above snippet right?
Sloth bearOP
it works!!! thanks a lot!!!