N
Nuxt2mo ago
nandi95

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
kapa.ai
kapa.ai2mo ago
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
// server/api/[...].ts
export default defineEventHandler(async (event) => {
const { API_URI } = useRuntimeConfig();
const path = event.path.replace(/^\/api\//, '');
const url = joinURL(API_URI, path);

// Get the auth token from the cookie
const authToken = getCookie(event, 'Authorization-Token');

return proxyRequest(event, url, {
headers: {
// Forward the auth token
Authorization: `Bearer ${authToken}`
}
});
});
// server/api/[...].ts
export default defineEventHandler(async (event) => {
const { API_URI } = useRuntimeConfig();
const path = event.path.replace(/^\/api\//, '');
const url = joinURL(API_URI, path);

// Get the auth token from the cookie
const authToken = getCookie(event, 'Authorization-Token');

return proxyRequest(event, url, {
headers: {
// Forward the auth token
Authorization: `Bearer ${authToken}`
}
});
});
Option 2: Forward cookies and headers You can also use the built-in utilities to forward cookies and headers:
// composables/fetch.ts
import { appendResponseHeader } from 'h3'
import type { H3Event } from 'h3'
export const fetchWithCookie = async (event: H3Event, url: string) => {
/* Get the response from the server endpoint */
const res = await $fetch.raw(url, {
headers: {
// Include the authorization header
Authorization: `Bearer ${getCookie(event, 'Authorization-Token')}`
}
})
/* Get the cookies from the response */
const cookies = res.headers.getSetCookie()
/* Attach each cookie to our incoming Request */
for (const cookie of cookies) {
appendResponseHeader(event, 'set-cookie', cookie)
}
/* Return the data of the response */
return res._data
}
// composables/fetch.ts
import { appendResponseHeader } from 'h3'
import type { H3Event } from 'h3'
export const fetchWithCookie = async (event: H3Event, url: string) => {
/* Get the response from the server endpoint */
const res = await $fetch.raw(url, {
headers: {
// Include the authorization header
Authorization: `Bearer ${getCookie(event, 'Authorization-Token')}`
}
})
/* Get the cookies from the response */
const cookies = res.headers.getSetCookie()
/* Attach each cookie to our incoming Request */
for (const cookie of cookies) {
appendResponseHeader(event, 'set-cookie', cookie)
}
/* Return the data of the response */
return res._data
}
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:
<script setup>
const { data } = await useFetch('/api/confidential', {
headers: useRequestHeaders(['cookie'])
})
</script>
<script setup>
const { data } = await useFetch('/api/confidential', {
headers: useRequestHeaders(['cookie'])
})
</script>
Docs > Api > Composables Protecting API Routes To ensure your API routes are properly protected, you can use the requireUserSession utility:
// server/api/user/stats.get.ts
export default defineEventHandler(async (event) => {
// make sure the user is logged in
// This will throw a 401 error if the request doesn't come from a valid user session
const { user } = await requireUserSession(event)

// Your API logic here
return {}
});
// server/api/user/stats.get.ts
export default defineEventHandler(async (event) => {
// make sure the user is logged in
// This will throw a 401 error if the request doesn't come from a valid user session
const { user } = await requireUserSession(event)

// Your API logic here
return {}
});
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: ----------------------
kapa.ai
kapa.ai2mo ago
<@478977928730902528> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
nandi95
nandi95OP2mo ago
I take it I have to do option one? no option for defining this as a routeRule
Cue
Cue2mo ago
@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.
nandi95
nandi95OP2mo ago
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 helpful
Cue
Cue2mo ago
Indeed that is the way forward, particularly if you’re sending headers that are dependent during runtime (e.g. access tokens)
nandi95
nandi95OP2mo ago
yeah thank you

Did you find this page helpful?