Next.js Redirect from / to another page Ask Question

Next.js Redirect from / to another page Ask Question

I'm new in Next.js and I'm wondering how to redirect from start page ( / ) to /hello-nextjs for example. Once user loads a page and after that determine if path === / redirect to /hello-nextjs

In react-router we do something like:

<Switch>
  <Route path="/hello-nextjs" exact component={HelloNextjs} />
  <Redirect to="/hello-nextjs" /> // or <Route path="/" exact render={() => <Redirect to="/hello-nextjs" />} />
</Switch>

ベストアンサー1

Update: Next.js >= 13 with AppDir enabled
You can use next/navigation to redirect both in client components and server components.

Ex. in pages :

import { redirect } from 'next/navigation';
export default async function Home({ params }) {
    redirect('/hello-nextjs');
  // ...
}

Ex. In client components:

'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';

export const Home= () => {
  const { push } = useRouter();

  useEffect(() => {
     push('/hello-nextjs');
  }, []);
  return <p></p>;
};

Update: Next.js >= 12.1
As @warfield pointed out in his answer from next.js >= 12.1 relative URLs are no longer allowed in redirects and using them will throw an error. I'm reposting here his answer for more visibility :

To redirect using middleware with Next.js >= 12.1:

  1. Create a middleware.ts (or .js) file at the same level as your pages directory
  2. Export a middleware function
  3. Create an absolute URL and pass it to redirect

TypeScript example middleware.ts:


import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {   
  const url = request.nextUrl.clone()   
  if (url.pathname === '/') {
    url.pathname = '/hello-nextjs'
    return NextResponse.redirect(url)   
  } 
}

Update: Next.js >= 12
Now you can do redirects using middleware, create a _middleware.js file inside the pages folder (or any sub folder inside pages)

import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req, ev) {
    const { pathname } = req.nextUrl
    if (pathname == '/') {
        return NextResponse.redirect('/hello-nextjs')
    }
    return NextResponse.next()
}

Update: Next.js >= 10

From Next.js 10 you can do server side redirects (see below for client side redirects) with a redirect key inside getServerSideProps or getStaticProps :

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
  // or use context.resolvedUrl for conditional redirect
  // if(context.resolvedUrl == "/")
  if (!data) {
    return {
      redirect: {
        destination: '/hello-nextjs',
        permanent: false,
      },
    }
  }

  return {
    props: {}, // will be passed to the page component as props
  }
}

Note: を使用すると、getServerSidePropsアプリはSSRに強制されます。また、ビルド時のリダイレクトはサポートされていません。ビルド時にリダイレクトがわかっている場合は、それらを内部に追加できます。次のconfig.js

next.jsリダイレクトできますページが読み込まれた後Router:

import Router from 'next/router'

componentDidMount(){
    const {pathname} = Router
    if(pathname == '/' ){
       Router.push('/hello-nextjs')
    }
}

またはフックを使用する場合:

import React, { useEffect } from "react";
import Router from 'next/router'

...
useEffect(() => {
   const {pathname} = Router
   if(pathname == '/' ){
       Router.push('/hello-nextjs')
   }
 });

リダイレクト前にフラッシュを防止したい場合は、簡単なトリックを使用できます:

import React, { useEffect,useState } from "react";
import Router from 'next/router'
const myPage = ()=>{
    const [loaded,setLoaded] = useState(false)
    useEffect(() => {
        const {pathname} = Router
        // conditional redirect
        if(pathname == '/' ){
            // with router.push the page may be added to history
            // the browser on history back will  go back to this page and then forward again to the redirected page
            // you can prevent this behaviour using location.replace
            Router.push('/hello-nextjs')
           //location.replace("/hello-nextjs")
        }else{
            setLoaded(true)
        }
      },[]);

    if(!loaded){
        return <div></div> //show nothing or a loader
    }
    return ( 
        <p>
            You will see this page only if pathname !== "/" , <br/>
        </p> 
    )
}
export default myPage

next.config.js一般的に、リダイレクトを使用したり、コンポーネントの条件付きレンダリングを使用したりできる場合にクライアント リダイレクトを実行するのは、良い/エレガントなアプローチではないと言えます。

上記の例をすべて含んだシンプルなリポジトリを作成しましたここ

おすすめ記事