How to implement a route guard in Next.js for protected routes



Image not found!!

In Next.js, you can implement a route guard by using a combination of the getServerSideProps or getStaticProps functions and the useRouter hook. This allows you to check whether a user is authenticated before rendering a protected route. Here's a simple example:

  1. Create a Higher-Order Component (HOC) for the route guard:
jsx
// components/ProtectedRoute.js import { useRouter } from 'next/router'; import { useEffect } from 'react'; const ProtectedRoute = ({ children }) => { const router = useRouter(); useEffect(() => { // Check if the user is authenticated, if not, redirect to the login page const isAuthenticated = /* Your authentication check logic here */ false; if (!isAuthenticated) { router.push('/login'); } }, [router]); return <>{children}</>; }; export default ProtectedRoute;
  1. Wrap your protected pages with the ProtectedRoute component:
jsx
// pages/protectedPage.js import ProtectedRoute from '../components/ProtectedRoute'; const ProtectedPage = () => { return ( <ProtectedRoute> <div> {/* Your protected page content */} <h1>Protected Page</h1> </div> </ProtectedRoute> ); }; export default ProtectedPage;
  1. Modify the getServerSideProps or getStaticProps function in your protected pages:

You can further enhance the route guard by adding server-side logic to check for authentication. For example, in a file like pages/protectedPage.js:

jsx
// pages/protectedPage.js import ProtectedRoute from '../components/ProtectedRoute'; const ProtectedPage = ({ user }) => { return ( <ProtectedRoute> <div> {/* Your protected page content */} <h1>Protected Page</h1> <p>Welcome, {user.username}!</p> </div> </ProtectedRoute> ); }; export const getServerSideProps = async (context) => { // Your authentication logic here const isAuthenticated = /* Your authentication check logic here */ false; if (!isAuthenticated) { // Redirect to login page if not authenticated return { redirect: { destination: '/login', permanent: false, }, }; } // Fetch user data or any other data needed for the page const user = /* Fetch user data */ { username: 'JohnDoe' }; return { props: { user }, }; }; export default ProtectedPage;

Note that the exact implementation might vary based on your authentication mechanism and requirements. Make sure to replace the placeholder authentication logic with your actual authentication check.