1

In pages I was able to navigate routes on the server by setting up a return statement in getServersideProps()

Before:

export const getServerSideProps = async (context) => {
    try {
    ..........
        // If token exists; redirect to '/' 
        if (token) {
            return {
                redirect: {
                    destination: `/`,
                    permanent: false,
                },
                props: {
                    // email, uid, token
                }
            }

        }

    } catch (err) {
        // either the `token` cookie didn't exist
        // or token verification failed
        // either way: allow user to stay on page to login
        return {
            props: {

            },
        };
    }
};

How can I do the same in the app router build?

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Ibra
  • 912
  • 1
  • 12
  • 31

1 Answers1

2

you could handle this in middleware.ts

import { getToken } from "next-auth/jwt";

 async function middleware(req) {
   
    const isAuthenticated = await getToken({ req });

    // you implement your logic

   if (!isAuthenticated) {
      return NextResponse.redirect(new URL("/login", req.url));
    }
}

// in the same file, you need to specify for which routes tou want to run this middleware

export const config = {
  matchter: ["/", "/dashboard"],
};

middleware docs

Ibra
  • 912
  • 1
  • 12
  • 31
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • That's correct! However, I couldn't use firebase admin module since it uses Node.js specific modules ('os' not supported) – Ibra Jun 21 '23 at 02:05
  • if you ask a separate question and create a reproducible example i can take a look at it – Yilmaz Jun 21 '23 at 02:11