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
}
2
Answers
By checking Header, secFetchSite, secFetchMode, userAgent we can confirm if the request is from browser
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:
Plus a config object if you want to limit to specific paths
export const config = { matcher: '/your-specific-path/:path*' };