Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect a page in Next.js for static export

Background: I have a tag page in my content based website that shows links to the pages that their content is tagged with the tag. But it turns out that my tagging system had a problem and now I want to prune the pages. So I need to redirect tags that only have one post in them to the single post. The following is what I tried so far:

export async function getStaticProps(context: any) {

  const res = await fetch(`${API_URL}/post/?tag=${context.params.tag}`)
  const posts = await res.json()

  for (var i = 0; i < posts.length; i++) {
    posts[i].link = '/blog/post/' + posts[i].slug;
  }
 
  if (posts.length===1){
    return {redirect: {
      permanent: true,
      destination: posts[0].link,
    },
  }
  }
  return {
    props: {
      posts: posts,
    },
  }
}

The Problem: The solution works when I run next locally. But it fails when I want to export the project to static.

So what is the appropriate way of redirecting for the current situation that works in static mode.

like image 669
Ehsan88 Avatar asked Sep 17 '25 06:09

Ehsan88


1 Answers

If you're using the static page by enabling output: "export" then you can use a redirect in server components. This approach also works with GitHub pages.

import { redirect } from 'next/navigation';
export default async function Home() {
    redirect('/new-page');
}
like image 127
MrAdib Avatar answered Sep 19 '25 22:09

MrAdib