How to Redirect Unauthenticated Users to Protected Routes in Next.js 13 App Directory

Posted by








Redirecting Unauthenticated Users with Protected Routes in Next.js 13 App Directory

Redirecting Unauthenticated Users with Protected Routes in Next.js 13 App Directory

In many web applications, there are pages or routes that should only be
accessible to authenticated users. In a Next.js 13 app directory, you can
implement protected routes and redirect unauthenticated users to a login
page or another location of your choice.

To create protected routes in a Next.js 13 app directory, you can make use
of the built-in authentication features such as the{” “}
getServerSideProps function and custom routing logic.

Using getServerSideProps for Authentication

The getServerSideProps function allows you to fetch data on
the server-side before the page is rendered. This makes it a suitable
place to perform authentication checks and redirect unauthenticated users
to the login page if necessary.

        
          export async function getServerSideProps(context) {
            // Perform authentication check
            const isAuthenticated = checkIfUserIsAuthenticated(context.req);
    
            if (!isAuthenticated) {
              return {
                redirect: {
                  destination: "/login",
                  permanent: false,
                },
              };
            }
    
            // Fetch page data
            const pageData = await fetchPageData();
    
            return {
              props: { pageData },
            };
          }
        
      

In the above example, the getServerSideProps function checks
if the user is authenticated using a custom
checkIfUserIsAuthenticated function. If the user is not
authenticated, a redirect object is returned to redirect the user to the
login page. If the user is authenticated, the page data is fetched and
passed to the page component as props.

Using Custom Routing Logic

Another approach to implementing protected routes in a Next.js 13 app
directory is to use custom routing logic in the page components. You can
create a higher-order component or a custom hook to handle authentication
checks and redirection.

        
          export const ProtectedRoute = ({ children }) => {
            const isAuthenticated = checkIfUserIsAuthenticated();
    
            if (!isAuthenticated) {
              // Redirect to login page
              return <Redirect to="/login" />;
            }
    
            return <>{children}</>;
          };
        
      

In this example, the ProtectedRoute component checks if the
user is authenticated using a custom
checkIfUserIsAuthenticated function. If the user is not
authenticated, the component redirects to the login page. If the user is
authenticated, the children of the component are rendered.

Conclusion

Implementing protected routes in a Next.js 13 app directory allows you to
control access to certain pages and routes based on user authentication
status. By using features such as getServerSideProps and
custom routing logic, you can redirect unauthenticated users to a login
page or another location of your choice, providing a secure and seamless
user experience.


0 0 votes
Article Rating
28 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Chris Lauer
7 months ago

Auth Helpers are deprecated

Huseyin
7 months ago

This was an amazing 5 minutes. Wonderful explanation from Jon. Please continue to produce amazing content such as this one.

Marc Vanrenterghem
7 months ago

Not very helpful since this approach will only work for Home page to redirect to the login page, or we would have to copy and paste the logic to every protected pages…

Ali Nazari
7 months ago

The problem with this approach is that the Home page (jsx, states, hooks) will be rendered which is unnecessary

Pushkar Kathayat
7 months ago

How to do it in client component?

App Stuff
7 months ago

yes please do a google auth sign in and sign out.

Kelvin Pompey
7 months ago

Does anyone know which VS Code theme is being used here?

Ashu Regmi
7 months ago

You are amazing thanks man – was stuck on this weird issue but this video helped 🙏

Madhav Kummara
7 months ago

This is such a bad way of implementing protected routes. Doing it this way, you would have to write repetitive code to check the authentication status. Use middleware or context provider instead.

Dave Benjamin
7 months ago

when i deploy to vercel, my builld fails unless I add `export const dynamic – 'force-dynamic'; I assume this is as a result of the cookies? Would love to see a vid explaining this behaviour…

Teagan Atwater
7 months ago

@Supabase @JonMeyers Currently NextJS throws the error "DynamicServerError: Dynamic server usage: cookies" when you try to do this unless a) you do it on a page or layout, and b) you include the line "export const dynamic = 'force-dynamic';" in your page/layout file. I'm not entirely clear as to why this is happening, but it's made it much more complicated to call "supabase.auth.getUser()" from within my server-rendered <Navbar />

Muhamad Nur
7 months ago

Hello how to fix, if i try getSession, always return null, but in local storage and cookies data all ready

Jason Gallavin
7 months ago

You shouldn't refresh an expired session. You should only refresh when it's not expired to extend the expirey. You are basically allowing a session to always be valid which is bad security practice

Mir Habib Ul Latif
7 months ago

if your middleware is not working then you need to place it on the src dir (same level as app)

Basic's School
7 months ago

is there any video how to reset pass cause i cant redirect to page update-password

Donovan Nagel
7 months ago

For me, the cookie doesn't do anything. I can log in fine, but if I try to getSession, it just returns null. I can see the cookie in devtools. Really not having much luck with nextjs app routes.

Victor F. Santos
7 months ago

Kind of off-topic: but which browser are you using on 01:10?

Grahfx
7 months ago

Why not using the middleware for that ?

Jason
7 months ago

Just what I needed. Thanks Jon!