N
Nuxt9mo ago
johnk

Set header from server middleware

Hello! I am trying to set the "Authorization" header from server middleware, for an API.
export default defineEventHandler(async (event) => {
const token = await $fetch('https://xxx.kinde.com/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
audience: "https://xxx.kinde.com/api",
grant_type: "client_credentials",
client_id: "xxx",
client_secret: "xxx",
})
}) as { access_token: string };

// I have tried
event.headers.set('authorization', token.access_token);
// I have tried
event.node.req.headers.authorization = token.access_token;
})
export default defineEventHandler(async (event) => {
const token = await $fetch('https://xxx.kinde.com/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
audience: "https://xxx.kinde.com/api",
grant_type: "client_credentials",
client_id: "xxx",
client_secret: "xxx",
})
}) as { access_token: string };

// I have tried
event.headers.set('authorization', token.access_token);
// I have tried
event.node.req.headers.authorization = token.access_token;
})
but nothing seems to be working. I am getting 403 forbidden from my API
const properties = await $fetch(`https://xxx.kinde.com/api/v1/users/${event.context.params?.user}/properties`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
const properties = await $fetch(`https://xxx.kinde.com/api/v1/users/${event.context.params?.user}/properties`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
1 Reply
johnk
johnkOP9mo ago
Hmmm noted. I simply want to add the token with every request automatically, without having to $fetch the token outright every time I want it. The docs say that one of the use cases for server middleware is adding headers so I was going by that. Thank you! How could I do this on the server side? e.g. from a server/api/xxx Maybe I need to rethink my approach. My goal is to avoid calling retrieving directly from the kinde api in the client, and instead accessing it through my server, so I can more easily have fine tuned control, and to do that I need to store the token I retrieve, and I would like to avoid retrieving it again and again outright (I want to hide it essentially.) Do you think it could be more reasonable as a series of composables instead? Awesome, sounds like a plan! Thank you very much for your help, I really appreciate it!
Want results from more Discord servers?
Add your server