I'm using Next.JS 14, I want to show a page to the client if the request is coming from a browser but if it's not from a browser redirect to another website. Base on this code section I've done the redirect part but there isn't any documentation for showing the page. I'd appreciate if you can help me out how to show the page. Thanks.
// for GET method
export async function GET(request) {
const headersList = headers();
if(!headersList.get("Accept").includes("text/html")) {
return NextResponse.redirect("https://example.com");
}
return Page(); //LAYOUT
}
While the previous answer should work, if performance is a concern you can also try setting up a middleware by creating a middleware.js file at the root of your project.
So for instance the middleware file should look something like the following:
import { NextResponse } from 'next/server';
export function middleware(request) {
const acceptHeader = request.headers.get('accept') || '';
if (!acceptHeader.includes('text/html')) {
return NextResponse.redirect('https://example.com');
}
// Proceed to render the page as usual
return NextResponse.next();
}
Plus a config object if you want to limit to specific paths
export const config = { matcher: '/your-specific-path/:path*' };