How to do server side redirect in Next.js application ?


How to do server side redirect in Next.js application ?

Page Router

If you are using page router then from inside your data fetching method you can return redirect.

export async function getServerSideProps(){
    if(!userIsAuthenticated()){
        // ## this will redirect to destination url
        return {
            redirect:{
                permanent : false,
                destination : 'https://www.google.com'
            }
        }
    }
}

App Router

If you are using App router in Next.js 13 then from inside your page you need to import redirect.

import { redirect } from 'next/navigation'

const Home = async () => {
  // ## this will direct to google
  redirect("http://www.google.com");
  return (
    <main>
      
    </main>
  )
}

export default Home;