Feb 2023: With the new app/ directory feature coming with NextJS13, the auth middleware from NextAuth isn't working (at least for me).
I figured out a way to protect frontend sites easily and fast.
But be aware that it is bad practice to protect only your frontend pages! Your API should be secured too!
Here's the code:
import { getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"
import { redirect } from 'next/navigation';
export default async function Page() {
const session = await getServerSession(authOptions)
if(session == null){
return redirect("api/auth/signin")
} else {
return (
<>
<h1 className=" text-2xl">Very secure Page</h1>
<pre>{JSON.stringify(session, null, 2)}</pre>
</>
)
}
}
middleware.ts
file is on the same directory level as your app folder and pages folder – Yesima