How to make authenticated fetch request using Tanstack query?
I am having trouble figuring this out. Apologies, if this is something very straightforward which I am missing.
How can I make an authenticated request to an API?
In Expo, I can do this,
What's the equivalent in Nextjs?
1 Reply
I'm using axios with Tanstack Query, so in my setup tanstack query is just a tool to make calls and cache responses.
First, I'm making a template header for axios to include cookies with each request. You can make multiple combination of template headers as per your need. (application/json and multipart/form-data depending on your need)
Second, im defining axios requests with request URLs for my protected routes.
That's it for frontend/NextJs part. withCredentials: true attribute will make sure to send the cookie and other auth headers. Now you gotta parse the request on backend. I'm using ExpressJs.
First I created an authMiddleware that will be included in each protected routes.
Notice I attached the userId to req if session exits. This is handy when you have to perform DB operation based on user and don't user id to be passed from frontend (security risk)
Finally, include the middleware in your protected routes.
the authController will be executed before processing validations and forwarding the request to controller.
@Ping hi... notice any security flaw in this approach?