How to redirect to subpage in Nextjs 14 with static build

Before we start:
Please not that this solution isn’t perfect but works in some cases.

Imagine you want to host your webpage on AWS with S3 and cloudfront distirbution.

Your page is written in Nextjs. You have two paths defining different languages eg. /pl , /enso your urls should looks like:

domain.xyz/pl/
domain.xyz/pl/contact

domain.xyz/en/
domain.xyz/en/contact

Your app folder can looks as follows:

folders structure

Let see how to setup default redirect from domain.xyz to subpath pl , en in Next:

// app/page.tsx
import { redirect } from 'next/navigation';

export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'pl' }];
}

export default async function Home() {
redirect('/pl');
}

In /app/page.tsx add redirect function which is useful for server side redirections.

Per docs:

  • Invoking the redirect() function throws a NEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown.

So in this case Next will show you correct page dynamically changing your page content in the browser.

Note that this solution is not a good option if you care about SEO. First request to the sever returns empty page with NEXT_REDIRECT error which is not meaningful for crawlers.


PS: If you run Next is server mode Next should return HTTP 307 or 308 if you use permanentRedirect.

PS2: It would be better to set up a redirect at the CloudFront level using, for example, Lambda functions, but sometimes it’s not possible.

Comments

Leave a Reply