AxiosInstance with auth
Answered
Sloth bear posted this in #help-forum
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.
9 Replies
@Sloth bear 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.
ts
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,
},
})
I would create a router handler or use server action so you could use the axios instance without exposing those secret.
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?
@Sloth bear does both of the ways require app folder n min next 13?
server action, yes
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?
if i use api route, then i can still use the above snippet right?
and you fetch the api route in your client
Sloth bearOP
it works!!! thanks a lot!!!