This video tutorial demonstrates how to secure server-side rendered (SSR) pages and APIs in a Next.js application using Clerk.dev, by adding authentication to protect the routes and ensuring only logged-in users can access them.
The video begins by offering insight into how Clerk can be used to add security to SSR pages and API routes in a Next.js application. The instructor assumes that the viewers are familiar with the initial setup of Clerk, for which they provide a link to another video.
The instructor discusses creating 'Sign in' and 'Sign up' components, and how to organize them into folders corresponding to the routes they represent. They show the code required for creating dynamic routes in Next.js using file-based routing patterns.
The instructor moves on to explain the use of withServerSideAuth
from Clerk for server-side pages. The function is used to wrap the usual getServerSideProps
which performs an asynchronous operation to check for a session ID in the request object. If there is no session ID, it means the user isn't authenticated, and they're redirected to the sign-in page with the intended destination saved for post-login navigation.
The final segment explains how to secure API routes using the requireAuth
middleware from Clerk. This ensures that all requests to the API are authenticated, returning a 401 unauthorized error if the user is not logged in. The protected API route is demonstrated to fetch and display cat facts dynamically when a button on the UI is clicked.
getServerSideProps
with Clerk's withServerSideAuth
.requireAuth
from Clerk, enforcing user authentication for API access.async function () { const results = await fetch('/api/route'); setFact(await results.json()); }
.