Next.js Authorization Tutorial: Protecting Your Routes

Next.js Authorization Tutorial: Protecting Your Routes

Aung Kyaw Nyunt
In this tutorial, we'll learn how to implement authorization in Next.js to ensure that only authenticated users can access certain pages or APIs.
We’ll cover both client-side and server-side authentication checks, manage cookies, and handle redirects.
1. Understanding the Basics of Authentication in Next.js
Next.js is a powerful framework for React, and it has excellent support for both server-side and client-side rendering. When building a web app that requires authentication, the general flow usually involves:
  • Verifying user credentials (e.g., email and password).

  • Storing an authentication token (e.g., JWT) in the user's browser (often in cookies or localStorage).

  • Protecting specific pages and API routes so that only authorized users can access them.
2. Setting Up Authorization with Cookies in Next.js
We'll use cookies to store the user's authentication token. This allows the user to stay logged in across different sessions, and the token can be sent with requests to protect routes.
2.1. Setting up API to Handle Login
Let’s assume you have an authentication API that validates the user and returns a token (e.g., JWT). We'll store this token in a cookie.
// pages/api/login.js import { setCookie } from 'cookies-next'; // Helper to handle cookies export default async function login(req, res) { const { email, password } = req.body; // Check credentials (You should use your own validation here) if (email === 'test@example.com' && password === 'password123') { const token = 'your-jwt-token'; // In a real application, generate JWT token // Set cookie with token setCookie('token', token, { req, res, maxAge: 60 * 60 * 24 * 7 }); // Cookie expires in 7 days return res.status(200).json({ message: 'Login successful' }); } return res.status(401).json({ message: 'Invalid credentials' }); }
2.2. Making API Requests with Authorization Token
Now, you can use this token in your API requests. For example, to fetch data from a protected route, you would include the token in the request headers.
// Utility function to fetch data with token const fetchDataWithAuth = async (url, token) => { const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, }, }); return await response.json(); };
3. Protecting Server-Side Routes with getServerSideProps
In Next.js, getServerSideProps runs on the server every time a page is requested. You can use this to check for the authentication token before rendering the page.
3.1. Redirect Unauthorized Users
If the user is not authenticated, you can redirect them to the login page.
// pages/protected-page.js import { parseCookies } from 'nookies'; // Package to handle cookies in Next.js export async function getServerSideProps(context) { const cookies = parseCookies(context); const token = cookies.token; // If token doesn't exist, redirect to login page if (!token) { return { redirect: { destination: '/login', // Redirect to login if no token permanent: false, // Temporary redirect }, }; } // Proceed to fetch protected data const data = await fetchDataWithAuth('https://api.example.com/protected', token); return { props: { data }, }; } export default function ProtectedPage({ data }) { return ( <div> <h1>Protected Content</h1> <p>Data: {JSON.stringify(data)}</p> </div> ); }
4. Handling Authorization on the Client Side
On the client-side, you may want to check whether the user is logged in before rendering specific components or pages.
We’ll use the useEffect hook to check for the authentication token and perform a redirect if necessary.
4.1. Redirecting Unauthenticated Users in Components
You can use the useRouter hook from Next.js to redirect unauthenticated users from the client side.
// components/ProtectedComponent.js import { useEffect } from 'react'; import { useRouter } from 'next/router'; import { parseCookies } from 'nookies'; // To parse cookies client-side const ProtectedComponent = () => { const router = useRouter(); const cookies = parseCookies(); const token = cookies.token; useEffect(() => { if (!token) { // If no token, redirect to login router.push('/login'); } }, [token]); return ( <div> <h2>This is a protected component.</h2> <p>If you are seeing this, you're logged in.</p> </div> ); }; export default ProtectedComponent;
5. Creating the Login Page
Now let's create the login page where users will provide their credentials to log in.
// pages/login.js import { useState } from 'react'; import { useRouter } from 'next/router'; export default function LoginPage() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const router = useRouter(); const handleLogin = async (e) => { e.preventDefault(); const response = await fetch('/api/login', { method: 'POST', body: JSON.stringify({ email, password }), headers: { 'Content-Type': 'application/json' }, }); const data = await response.json(); if (response.status === 200) { router.push('/protected-page'); // Redirect to protected page after successful login } else { alert(data.message); // Show error if login fails } }; return ( <div> <h1>Login</h1> <form onSubmit={handleLogin}> <div> <label>Email</label> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required /> </div> <div> <label>Password</label> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required /> </div> <button type="submit">Login</button> </form> </div> ); }
6. Logging Out
To log out a user, you simply need to delete the authentication token from the cookies and redirect them to the login page or home page.
// pages/api/logout.js import { deleteCookie } from 'cookies-next'; export default function logout(req, res) { deleteCookie('token', { req, res }); return res.status(200).json({ message: 'Logged out successfully' }); }
// In your component, add logout functionality const handleLogout = async () => { await fetch('/api/logout'); window.location.href = '/login'; // Redirect to login after logout };
7. Protecting API Routes
To protect an API route, you need to verify the authentication token sent with the request. Here's how you can protect API routes in Next.js:

// pages/api/protected-api.js import { parseCookies } from 'nookies'; export default async function handler(req, res) { const cookies = parseCookies({ req }); const token = cookies.token; if (!token) { return res.status(401).json({ message: 'Unauthorized' }); } // Your protected API logic here... res.status(200).json({ message: 'This is protected data' }); }
8. Conclusion
In this tutorial, we have:
  • Learned how to set up authentication using cookies in Next.js.

  • Protected routes and APIs with server-side checks using getServerSideProps.

  • Implemented client-side checks with useEffect and useRouter.

  • Created a simple login page and logout functionality.


Now, you can ensure that only authenticated users can access certain pages and APIs, providing a secure and seamless user experience for your Next.js app.
https://www.applix.info
© All right Reserved. Inspired Codes...
Get In Touch
Rule and Policy