You are an admin, welcome!
; + } + + returnYou are not authorized to view this page!
; +} +``` + +#### Option 2: Protection through middleware + +This is only supported if we use the `jwt` session strategy. + +Create a `middleware.ts` file on the root or src directory (same level as where you store your pages) to protect all pages. Adding this +file makes users **require authentication**. If they aren’t authenticated, it redirects them to the sign-in page by default. Below is an +example of basic `middleware.ts` setup: + +```tsx +/* +if you only have this line, it protects all pages from unauthenticated users +and redirects them to the sign in page by default +*/ +export { default } from "next-auth/middleware" + +// add this line to choose/whitelist pages to secure +export const config = { matcher: ["/dashboard", "/admin"] } +``` + +If we want something more advanced then just securing pages from unauthenticated users, we need to wrap the middleware with `withAuth`. +Using this wrapper, we have 2 more options to protect our admin pages. **(Option 1)** we can use the `authorized` callback, which if +false, redirects the user to the sign in page (I’m not aware if you can customize the redirection). **(Option 2)** we can use the +middleware function inside the wrapper and add our own custom logic. Below is an example that shows both options: + +```tsx +import { withAuth } from "next-auth/middleware"; + +export default withAuth( + /* Option 1 */ + // `withAuth` augments your `Request` with the user's token. + function middleware(req) { + if ( + req.nextUrl.pathname.startsWith("/admin") && // not sure if first condition is necessary, just saw it in an example + req.nextauth.token.role != "admin" + ) + return NextResponse.rewrite(new URL("/Denied", req.url)); + }, + /* Option 2 */ + { + callbacks: { + authorized: ({ token }) => token?.role === "admin", + }, + }, +) + +export const config = { matcher: ["/admin"] } +``` + +## 🛡️Another Method for Protection and Authentication + +### Page Authentication + +- The code example below shows a simple way to do FE authentication +- The example below takes advantage of NextJs’s server side rendering +- We get the session data on the server and then our component will have access to this session by calling useSession(). +useSession() will access the props key from the return value of `getServerSideProps()` +- Alternatively, we can retrieve session info on the client side by just using `useSession()` and eliminating `getServerSideProps` + +```tsx +import { getServerAuthSession } from "../server/auth"; +import { GetServerSideProps } from "next"; +import { useSession } from "next-auth/react"; + +export const getServerSideProps: GetServerSideProps = async (ctx) => { + const session = await getServerAuthSession(ctx); + return { + props: { session }, + }; +}; + +const User = () => { + const { data: session } = useSession(); + // NOTE: session won't have a loading state since it's already prefetched on the server + + return ( +Email: {session.user.email}
+You are not authenticated
+ )} +