Proxy with header
What is the recommended way to proxy requests?
My frontend will log in using auth0. The access token is needed to talk to the api at a subdomain.
Currently the access_token is in the session cookie encrypted(secret)
7 Replies
Hi @nandi95. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Based on the knowledge sources, there are two recommended approaches for proxying requests in Nuxt while handling authentication tokens:
Recommended Proxy Approaches
According to the YouTube video on Nuxt proxying strategies, there are two recommended approaches:
1. Nitro proxy API endpoint - Creating a server route that forwards requests to your API
2. Proxy routeRule - Using Nitro's route rules for proxying
Nuxt 3: The BEST way to proxy your API in Nuxt
Handling Authentication with Proxy
Since you have your access token stored in an encrypted session cookie, here's how you can implement a proxy that forwards this token to your API:
Option 1: Create a Nitro proxy endpoint
Option 2: Forward cookies and headers
You can also use the built-in utilities to forward cookies and headers:
Docs > Getting-started > Data Fetching
Using useRequestHeaders for proxying
For client-side components that need to make authenticated requests, you can use
useRequestHeaders
to forward the authorization header:
Docs > Api > Composables
Protecting API Routes
To ensure your API routes are properly protected, you can use the requireUserSession
utility:
Docs > Guide > Recipes > Sessions and Authentication
This approach ensures that your API routes are protected and only accessible to authenticated users, while properly forwarding the authentication token to your API.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@478977928730902528> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
I take it I have to do option one? no option for defining this as a routeRule
@nandi95 you can proxy via
routeRules
, it is covered in the documentation. However, this method will drop certain headers, specifically the Accept
header, which can lead to problems if your API depends on it. For example, in Laravel, exceptions are rendered as HTML if the Accept
header is not set accordingly.indeed I guess the question was if I can dynamically add headers: Authorization one specifically
no matter there's an h3 thing called
proxyRequest
whihc is helpfulIndeed that is the way forward, particularly if you’re sending headers that are dependent during runtime (e.g. access tokens)
yeah
thank you