Pass custom headers to rewrites proxy #19078
Replies: 17 comments 27 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.
-
For anyone still grappling with this issue, you don't have to choose between using middleware and using nextjs rewrites. You can set the authorization (or whatever) headers you need in the middleware, and then let the normal rewrites in the next.config do the rewrite part. middlware.ts import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-hello-from-middleware1", "hello");
requestHeaders.set("Authorization", "Bearer ******");
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
return response;
}
export const config = {
matcher: "/api/auth/:slug*",
}; next.config.js async rewrites() {
return [
{
// source: "/api/auth/:slug*",
source: "/api/auth/:slug*",
destination: "https://postman-echo.com/get",
},
];
}, going to localhost:3000/api/auth will then return the response from postman-echo including the headers we set in the middleware. It's a bit impractical splitting the setup over two files in different parts of the project, but this way you don't have to deal with a lot of regex stuff as that's handled by the parts of Next meant to handle that. Middleware attaches the headers and config rewrites actually rewrite stuff. Works for me. |
Beta Was this translation helpful? Give feedback.
-
Somewhat related - does anyone know how |
Beta Was this translation helpful? Give feedback.
-
I get all of the above... however, why is a combination of async rewrites() and async headers() in next.config.js not working? In theory, as it is described in the documentation this should do the trick or am I completely mistaken?
|
Beta Was this translation helpful? Give feedback.
-
middleware invocations ($$$) shouldn’t be required for this |
Beta Was this translation helpful? Give feedback.
-
It would be nice to be able to set |
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