Authentication determines who a user is. Authorization determines what that user is allowed to do.
A secure Next.js application needs both.
After authentication, the application needs a mechanism for remembering the user's identity across requests.
Two common approaches are session-based authentication and token-based authentication.
Session-based systems store session state on the server and provide the client with a session identifier.
JWT-based systems encode claims into a signed token.
Neither approach is automatically more secure. The implementation and threat model matter.
OAuth providers such as Google and GitHub allow users to authenticate without the application handling their passwords.
The application receives identity information through the provider's authentication flow.
OAuth should be implemented using established libraries rather than manually reproducing the protocol.
If an application manages passwords directly, passwords must never be stored as plaintext.
They should be processed using a password hashing algorithm designed for password storage.
Authentication systems should also protect against brute-force attempts.
Authentication cookies should use appropriate security attributes.
Important settings include:
HttpOnly prevents client-side JavaScript from directly reading the cookie.
Secure ensures the cookie is transmitted only over HTTPS.
SameSite can reduce certain cross-site request attacks.
After identifying a user, every protected operation should verify whether the user has permission.
For example, being authenticated does not automatically mean that a user can modify every project in a database.
Authorization should happen on the server.
Next.js middleware can be useful for protecting route access and redirecting unauthenticated users.
However, middleware should not be considered the only security boundary.
Sensitive operations must perform authorization checks at the server-side operation itself.
A secure authentication system should:
Authentication is therefore an application-wide security architecture rather than simply adding a login page.