In Next.js, you can achieve such redirects by using the useRouter
hook provided by next/router
. Here's how you can redirect from the start page /
to /hello-nextjs
based on a condition:
1. First, ensure you have next/router
installed in your Next.js project. If not, you can install it using npm or yarn:
npm install next/router
or
yarn add next/router
2. In your component, you can use the useRouter
hook to get the current route information and perform a redirect if the condition matches:
import { useRouter } from 'next/router';
const HomePage = () => {
const router = useRouter();
// Check if the path is '/'
if(router.asPath === '/') {
// Redirect to '/hello-nextjs'
router.push('/hello-nextjs');
}
return (
<div>
{/* Your homepage content */}
</div>
);
};
export default HomePage;
3. Make sure to update the HomePage
component with your actual content and structure.
4. When a user accesses the root path /
, the HomePage
component will check the route using useRouter
and if it matches /
, it will redirect the user to /hello-nextjs
.
This way, you can achieve conditional redirects in Next.js similar to how you would do it in react-router
.