Update
Using NextAuth.js with a Custom Provider and Custom Database
NextAuth.js allows you to create custom authentication providers and use a custom database to store user data. Just make sure you are doing all these steps.
- install NextAuth.js:
npm install next-auth
- Create a Custom Provider:
Create a custom authentication provider with app (next.js 13) at this directory
app/api/auth/[...nextauth]/route.js.
and this file should be like this:
import { NextApiRequest, NextApiResponse } from 'next'
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
export default NextAuth({
providers: [
Providers.Credentials({
// The name to display on the sign-in form (e.g., "Sign in with...")
name: 'Custom Credentials',
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" }
},
authorize: async (credentials) => {
// Your custom authentication logic here
// You can query your user data directly to db here. It is safe.
const user = { id: 1, name: "John Doe" }; // Replace with your user data logic
if (user) {
return user;
} else {
// if user not found or logic not accepted.
return null
}
},
}),
],
session: {
jwt: true,
},
callbacks: {
async jwt(token, user) {
if (user) {
token.id = user.id;
token.name = user.name;
}
return token;
},
},
pages: {
signIn: '/auth/signin', // your custom page
},
callbacks: {
async session(session, token) {
// if you need to add more info in session
session.user.id = token.id;
session.user.name = token.name;
return session;
},
},
});
- Usage in Your Application:
You can now use your custom authentication provider in your Next.js components. Here's an example of a login form:
// app/auth/signin.js (this our page)
import { signIn } from 'next-auth/react' // login the user
export default function SignIn() {
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const credentials = {
username: formData.get('username'),
password: formData.get('password'),
};
const result = await signIn('credentials', { ...credentials, redirect: false });
if (!result.error) {
// Successfully logged in
// Redirect or perform any necessary actions
} else {
// Handle authentication error
console.error(result.error);
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Sign In</button>
</form>
);
}
- Finally If you wanna get user data you can simply:
// any component file
import { useSession } from 'next-auth/react'
export default function Component({}) {
const { status, data } = useSession()
return (
<div>
{status === 'loading' ? (
<>Loading ...</>
) : status === 'unauthenticated' ? (
<>No User Logged In</>
) : (
<span>
There is authenticated user <br />
{data?.user.username}
</span>
)}
</div>
)
}
That is it. Let me know if you need more help. Happy Coding!