Next.js - Imperative Routing



In Next.js, routing can be achieved declaratively using the <link> component or imperatively through programmatic navigation. So far we learned declarative routing and it's implementation. In this chapter we will learn, what is imperative routing, how to implement it and how to define a routing based on programmatic conditions.

What is Imperative Routing?

Imperative routing is a method of navigating programmatically based on certain condition or user action such as clicking button. This approach is particularly useful when navigation depends on user authentication status, dynamic condition and custom business logic.

Imperative Routing using useRouter

To implement imperative routing, Next.js provides useRouter hook to redirect or navigate between routes at the client side. This hook can only be used in client side components. This is useful when we want redirect user to home page or any other page after clicking a button or submitting a form.

Example

In the example below, we implemented a product ordering feature to the product page we created in the previous chapters. On clicking the button, user will get a confirmation of the order and redirect them to home page using 'useRoute' hook.

"use client"; 

import { useRouter } from "next/navigation";
import { PageProps } from "next/dist/shared/lib/router/utils/page-props";

export default function ProductPage({ params }: PageProps) {
    const router = useRouter();

    const handleClick = () =>{
        alert("Order Placed...");

        // Navigate to home page after placing order
        router.push("/");
    };
    return (
        <div>
            <h1>Product {params.id}</h1>
            <p>This is the product page for item {params.id}</p>
            <button onClick={handleClick}>Order Item</button>
        </div>
    );
}

Output

In the output, after placing order user is getting redirected to home page.

next.js-navigating-dynamically

Routing Based on Condition

We can use useRouter hook to define routing URL based on certain conditions like if user is authenticated or logged in. See the example below.

Example

In the example below, we defined a next.js client components to check if user is authenticated and display login page or protected page based on it. We kept userAuthenticated as false, so that redirecting will be visible in output.

// app/protected-page/page.tsx file

"use client";

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

export default function ProtectedPage() {
  const router = useRouter();

  useEffect(() => {
    // Replace with actual authentication logic
    const userAuthenticated = false; 
    if (!userAuthenticated) {
      router.replace('/login'); // Redirect to login page
    }
  }, [router]);

  return <div> Welcome to the Protected Page </div>;
}

// app/login/page.tsx file

export default function Login() {
    return (
      <div>
        <h2>Login</h2>
        <div>
          <label htmlFor="username">Username:</label>
          <input type="text"/>
        </div>
        <div>
          <label htmlFor="password">Password:</label>
          <input type="password"/>
        </div>
        
        <button type="submit">Login </button>
      </div>
    );
}

Output

In the output, when we are trying to access protected page, we are getting redirected to login page.

next.js-imperative-routing
Advertisements