Skip to main content

Credentials authentication

NextAuth.js is built in a way that is flexible to integrate it with any authentication back-end you or your company may already have.

This library has been designed to handle the user session client-wise, to support multiple authentication methods (OAuth, Email, etc...) so that you're not forced to run your own authentication service.

In case you already have an authentication service, you can use the Credentials Provider, which will just forward the credentials inserted by the user in the login form to your service.

For this tutorial, we're going to use NextAuth.js example app as a base.

danger

The functionality provided for credentials based authentication is intentionally limited to discourage use of passwords due to the inherent security risks associated with them and the additional complexity associated with supporting usernames and passwords.

Integrating the Credentials Provider is as simple as initializing it in the NextAuth.js configuration file:

pages/api/auth/[...nextauth].ts
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"

export default NextAuth({
providers: [
CredentialsProvider({
async authorize(credentials) {
const authResponse = await fetch("/users/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(credentials),
})

if (!authResponse.ok) {
return null
}

const user = await authResponse.json()

return user
},
}),
],
})
note

Check the Credentials Provider options for further customization

Note that we only need to define an authorize method that is in charge of receiving the credentials inserted by the user and call the authorization service.

info

If you're using TypeScript, you can augment the User interface to match the response of your authorize callback, so whenever you read the user in other callbacks (like the jwt) the type will match correctly.