I have used breeze-next as a boilerplate.
User register and login work perfectly but when I create a custom hook to interact with the server, Axios sends requests to front-end address, instead of the server.
I have declared the server address in .env
file:
NEXT_PUBLIC_BACKEND_URL=http://localhost:8000
Axios configuration:
import Axios from 'axios'
const axios = Axios.create({
baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
withCredentials: true,
})
export default axios
My custom hook:
export const useAccount = () => {
const csrf = () => axios.get('/sanctum/csrf-cookie')
const {data: user, error, mutate} = useSWR('/api/user', () =>
axios
.get('/api/user')
.then(res => res.data)
.catch(error => {
if (error.response.status !== 409) throw error
router.push('/verify-email')
}),
)
const start = async ({setErrors, setStatus, ...props}) => {
await csrf() // <-- Fails Here
axios.post('/user/account/start', props)
.then(() => mutate())
.catch(error => {
setErrors(Object.values(error.response.data.errors).flat())
})
}
return {
start
}
}
When axios sends a get request it sends the request to http://localhost:3000/sanctum/csrf-cookie
which is the front-end address.
The problem was with wrong import.
I didn't pay attention to what file is IDE importing as axios into account Hook.
It was like this:
import axios from "axios"
So I changed it to:
import axios from "@/lib/axios"