Pass custom headers to rewrites proxy #19078
Replies: 12 comments 20 replies
-
Yeah, this would be great! If I'm understanding @lfender6445 correctly, it'd be something like: module.exports = {
/* … */,
async rewrites() {
return [
{
source: '/blog/:path*',
destination: 'https://some.external.blog/:path*',
headers: {/* … */}
},
];
},
}; |
Beta Was this translation helpful? Give feedback.
-
Yes! I would love this because i'm struggling to add an |
Beta Was this translation helpful? Give feedback.
-
I would also find this very useful. I am attempting to proxy a legacy service that would require some custom headers on the proxied request. I was able to get around this with an API route that is utilizing http-proxy-middleware (Thanks to this post), but this feels brittle in the long run. I was also able to get this to work by adding a |
Beta Was this translation helpful? Give feedback.
-
Also in need of this feature to distinguish between proxied request and normal request. I am proxying some paths to endpoints in the same project . But unable to distinguish between proxied and direct request. I think there should be an option to pass headers to proxy request. It will solve a lot of use case @timneutkens . Is this feature planned in upcoming release ? @BrendanDavies PR looks like the solution |
Beta Was this translation helpful? Give feedback.
-
You can now self-serve custom routing, including rewrites, using Middleware: https://nextjs.org/docs/middleware |
Beta Was this translation helpful? Give feedback.
-
Any updates on this? |
Beta Was this translation helpful? Give feedback.
-
Posting this to save time for others that come across. My situation is I need a middleware to download files but the server that had the files need a special auth header. Here's how I did it with axios to download the file. Keep in mind this using the // _middleware.ts
import { NextRequest, NextResponse } from 'next/server'
import axios from 'axios'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
const API_URL = "YOUR_API_URL"
export async function middleware(nextRequest: NextRequest) {
// match route
if (nextRequest.nextUrl.pathname.startsWith('/download/attachments/')) {
// get the requested id from the pathname
const documentId = nextRequest.nextUrl.pathname.split('/').pop()
// get auth token - this is currently stored in the users cookie
let authToken
try {
authToken = JSON.parse(nextRequest.cookies.auth).access_token
} catch (error) {
console.log(`Tried to download document ${documentId} but had no auth cookie`)
}
// Make sure the document id is a number
if (documentId.match(/[0-9]+/) && authToken) {
// Create special axios instance that uses the fetch adapter (was getting stream errors without this)
const axiosInstance = axios.create({
adapter: fetchAdapter
})
// Use special axios instance to download the file
return axiosInstance
.get(`${API_URL}/${documentId}`, {
headers: { Authorization: `Bearer ${authToken}` }, // Here is where the auth header is added
responseType: 'arraybuffer'
})
.then(axiosResponse => {
// Pass on data and headers to the NextResponse
const resBuffer = Buffer.from(axiosResponse.data)
return new NextResponse(resBuffer, {
headers: axiosResponse.headers,
status: axiosResponse.status
})
})
.catch(error => {
// Pass on data and erros to the NextResponse
const resBuffer = Buffer.from(error.response.data)
return NextResponse.json(JSON.parse(resBuffer.toString()), {
status: error.response.status
})
})
}
}
} |
Beta Was this translation helpful? Give feedback.
-
For those watching this issue - I've created a draft PR that exposes the upstream proxy config which allows setting headers (as well as other options which I needed for our use case). #40277. Still working through whatever other steps I need to do according to the contributing guidelines. |
Beta Was this translation helpful? Give feedback.
-
how to include bearer token when rewrite?
|
Beta Was this translation helpful? Give feedback.
-
I think something like this should work: import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export const config = {
matcher: '/product/:path',
};
// Proxies /product/:id to https://my-proxied-site.com/product/:id
export function middleware(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
requestHeaders.set('Authorization', 'Bearer ******');
// Extract product id from pathname
const [, , id] = request.nextUrl.pathname.split('/');
request.nextUrl.href = `https://vercel.com/product/${id}`;
return NextResponse.rewrite(request.nextUrl, {
request: {
headers: requestHeaders,
},
});
} |
Beta Was this translation helpful? Give feedback.
-
Can I use middleware to just deal with the custom header and still use the rewrite to deal with rewrites? It would be very appreciated if we could define custom headers for rewrites without involving middleware to keep the middleware as simple as possible. |
Beta Was this translation helpful? Give feedback.
-
Would be nice if it's as simple as Vite's
|
Beta Was this translation helpful? Give feedback.
-
Feature request
Is your feature request related to a problem? Please describe.
I would like to pass custom header values to my fallback application
Describe the solution you'd like
something close to this https://nextjs.org/docs/api-reference/next.config.js/headers
Describe alternatives you've considered
I have tried supplying the custom header using methods outlined in https://nextjs.org/docs/api-reference/next.config.js/headers but checking here it appears that headers are not passed to the proxy, at-least not in a way I'd expect.
Additional context
In my case, the proxied application sits behind cloudflare firewall that can only be bypassed with specific header kvp
Beta Was this translation helpful? Give feedback.
All reactions