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.
get started with supabase for free here: https://app.supabase.com/?utm_source=youtube&utm_medium=video&utm_term=jon&utm_content=ywvXGW6P4Gs
Auth Helpers are deprecated
This was an amazing 5 minutes. Wonderful explanation from Jon. Please continue to produce amazing content such as this one.
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…
The problem with this approach is that the Home page (jsx, states, hooks) will be rendered which is unnecessary
How to do it in client component?
yes please do a google auth sign in and sign out.
Does anyone know which VS Code theme is being used here?
You are amazing thanks man – was stuck on this weird issue but this video helped 🙏
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.
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…
@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 />
Hello how to fix, if i try getSession, always return null, but in local storage and cookies data all ready
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
if your middleware is not working then you need to place it on the src dir (same level as app)
is there any video how to reset pass cause i cant redirect to page update-password
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.
Kind of off-topic: but which browser are you using on 01:10?
Why not using the middleware for that ?
Just what I needed. Thanks Jon!