DEV Community

Shameel Uddin
Shameel Uddin

Posted on

Next.js 13 | Redirect To Different URL in Server Component vs. in Client Component

I just shifted to Next.js 13 (pretty late in the game, I know) but I faced a little bit issue with re-direction so posting a quick article about it.

Note: Don't be confused about session in the below example. I used next-auth to get the session on root page and based on that, I re-direct a person to either login page or dashboard page.

You can implement this logic as per your own use-case.


  • Use redirect for Server Side Components.
  • Use useRouter for Client Side Components.

Redirecting To Different URL in Server Component

Use redirect:

import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";

export default async function Home() {
  const session = await getServerSession(authOptions);
  if (session?.accessToken) {
  } else {

Enter fullscreen mode Exit fullscreen mode

Read more about redirect here

Redirecting To Different URL in Client Component

Implement useRouter:

"use client";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

export default function Home() {
  const router = useRouter();
  const { data: session } = useSession();
  if (session?.accessToken) {
Enter fullscreen mode Exit fullscreen mode

Read more about useRouter here

One such example I implemented for client side is this:

const handleClick = async () => {
    const { userName, password } = formData;
    const data = await signIn("credentials", {
      redirect: false,
    if (data?.status === 200) {
Enter fullscreen mode Exit fullscreen mode

In this example, I used next-auth to verify credentials in login page and redirected the user to dashboard.

I might be writing about next-auth in future articles as well. This one was mainly for redirecting the user in next.js 13 in server and client side components.

Hope that helps =)

Follow me for more of such content:

Top comments (0)