Protecting Resources
Protecting routes can be done generally by checking for the session and taking an action if an active session is not found, like redirecting the user to the login page or simply returning a 401: Unauthenticated
response.
Pages
You can protect routes by checking for the presence of a session and then redirect to a login page if the session is not present. This can either be done per route, or for a group of routes using a middleware such as the following:
import { getSession } from "@auth/express"
export async function authenticatedUser(
req: Request,
res: Response,
next: NextFunction
) {
const session = res.locals.session ?? (await getSession(req, authConfig))
if (!session?.user) {
res.redirect("/login")
} else {
next()
}
}
import { authenticatedUser } from "./lib.ts"
// This route is protected
app.get("/profile", authenticatedUser, (req, res) => {
const { session } = res.locals
res.render("profile", { user: session?.user })
})
// This route is not protected
app.get("/", (req, res) => {
res.render("index")
})
app.use("/", root)
API Routes
Protecting API routes in the various frameworks can also be done with the auth
export.
API Routes are protected in the same way as any other route in Express, see the examples above.
Next.js Middleware
With Next.js 12+, the easiest way to protect a set of pages is using the middleware file. You can create a middleware.ts
file in your root pages directory with the following contents.
export { auth as middleware } from "@/auth"
Then define authorized
callback in your auth.ts
file. For more details check out the reference docs.
import NextAuth from "next-auth"
export const { auth, handlers } = NextAuth({
callbacks: {
authorized: async ({ auth }) => {
// Logged in users are authenticated, otherwise redirect to login page
return !!auth
},
},
})
You can also use the auth
method as a wrapper if you’d like to implement more logic inside the middleware.
import { auth } from "@/auth"
export default auth((req) => {
if (!req.auth && req.nextUrl.pathname !== "/login") {
const newUrl = new URL("/login", req.nextUrl.origin)
return Response.redirect(newUrl)
}
})
You can also use a regex to match multiple routes or you can negate certain routes in order to protect all remaining routes. The following example avoids running the middleware on paths such as the favicon or static images.
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
}
Middleware will protect pages as defined by the matcher
config export. For more details about the matcher, check out the Next.js docs.
You should not rely on middleware exclusively for authorization. Always ensure that the session is verified as close to your data fetching as possible.