Search code examples
reactjsnext.jsnext-auth

Redirect all routes to home page if user not logged in


I have an app which is basically an admin portal for an e-commerce site. I think it's best that users not be able to access any routes without first being logged in. I am using NextJS 13 (with the app router) and next-auth.

I am aware of some of the ways to protect individual routes. However, is there a way to redirect any and all routes--in this case, to the home page--when no user is logged in. I think before, we were able to do this with the _app.js component in earlier versions of NextJS. However, I believe that this is no longer an option when using the app router.

Below is an example of how I am currently handing redirects when there is no user:

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

const ProductsPage = () => {
  const { data: session } = useSession();
  const router = useRouter();

  if (!session) {
    router.push("/");
  }

  return (
    <div>
      <Link href="/products/new">
        <button className="bg-gray-300 rounded-md py-1 px-2">
          Add new product
        </button>
      </Link>
      <table className="basic mt-4">
        <thead>
          <tr>
            <td>Product</td>
            <td></td>
          </tr>
        </thead>
        <tbody>
          {products.map((product) => (
            <tr key={product._id}>
              <td>{product.name}</td>
              <td>
                <EditButton href={`/products/edit/${product._id}`} />
                <DeleteButton href={`/products/delete/${product._id}`} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default ProductsPage;

However, I have a good amount of pages and do not want to have to do this for every single page. This also causes flickering. It first renders the product page and then, redirects to the home page after determining that there is no active session.


Solution

  • Use the Middleware feature of Next.js and check for the authentication and redirection inside of it.

    export async function middleware(req: NextRequest) {
      // validate the user is authenticated
      const verifiedToken = //check for auth
      const { origin } = req.nextUrl;
    
      // redirect if the token is invalid
      if (!verifiedToken) {
        return NextResponse.redirect(`/login`);
      }