How do you use NextResponse.rewrite() in a Route Handler? #59115
Replies: 6 comments
-
I have the same question and I'm on the hunt for a better answer. Currently my route handler is throwing this Error:
My code: import { NextResponse } from 'next/server';
export async function GET( request ) {
// Get the search params from the request
const searchParams = request?.nextUrl?.searchParams;
// Get the error from the search params
const error = {
type: searchParams?.get( "error" ),
};
// Add the error to a custom response header
if ( error ) {
request.headers.set( 'x-error', JSON.stringify( error ) );
}
// Rewrite to /error
return NextResponse.rewrite( new URL( '/error', request?.url ) );
} |
Beta Was this translation helpful? Give feedback.
-
Any updates? |
Beta Was this translation helpful? Give feedback.
-
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#redirects |
Beta Was this translation helpful? Give feedback.
-
Any news about this issues? |
Beta Was this translation helpful? Give feedback.
-
Would be nice to have this functionality! I need to proxy a call to another service and modify the authorization header to work with the third-party service. Something like: export async function GET() {
const accessToken = '...'
return NextResponse.rewrite(
new URL("http://thirdparty.example/"),
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
} |
Beta Was this translation helpful? Give feedback.
-
In my case I wanted "catch all" route handler that will proxy requests to github, e.g.: app/[...slug]/route.ts import { NextRequest } from 'next/server'
import { cookies } from 'next/headers'
async function handler(req: NextRequest) {
const url = new URL(req.url)
const response = await fetch(new URL(url.pathname + url.search + url.hash, 'https://api.github.com/'), {
method: req.method,
headers: {
...req.headers,
authorization: `Bearer ${cookies().get('access_token')?.value}`,
},
body: req.method !== 'GET' && req.method !== 'HEAD' ? await req.blob() : null,
})
const body = await response.blob()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: { ...response.headers },
})
}
export const GET = handler
export const POST = handler with this in place, from cliend side I may do something like: fetch('/user').then(r => r.json()).then(console.log) as well as await fetch('/graphql', {method: 'POST',headers: {'content-type': 'application/json'}, body: JSON.stringify({query:'{viewer{login}}'})}).then(r => r.json()) profit
|
Beta Was this translation helpful? Give feedback.
-
I need to rewrite a response after turning on the draftMode, for this, I set a route handler inside app/api/enable-preview/route.ts
When you call the API it gives an error saying that NextResponse.rewrite() in route handlers is not supported yet.
Do you have any updates on that?
Thank you,
Federico Peloso
Beta Was this translation helpful? Give feedback.
All reactions