how to redirect programatically in nextjs

To redirect programmatically in Next.js, you can make use of the next/router module. The following steps outline the process:

  1. Import the useRouter hook from next/router:
import { useRouter } from 'next/router';
  1. Within your functional component, initialize the router using the useRouter hook:
const router = useRouter();
  1. Use the router.push() method to redirect to the desired page. This method accepts the URL as a parameter:
router.push('/path/to/redirect');

Here is an example of how these steps can be implemented in a Next.js component:

import { useRouter } from 'next/router';

const MyComponent = () => {
  const router = useRouter();

  const handleRedirect = () => {
    router.push('/path/to/redirect');
  };

  return (
    <div>
      <button onClick={handleRedirect}>Redirect</button>
    </div>
  );
};

export default MyComponent;

In this example, when the button is clicked, the handleRedirect function is called, which uses the router.push() method to redirect to the specified URL.

By following these steps, you can programmatically redirect in Next.js using the next/router module.