To implement an authentication flow using NextAuth.js with Next.js 14 and the App Router feature, you need to integrate your existing API logic within NextAuth's custom provider configuration. NextAuth.js is a powerful authentication library for Next.js, which allows you to handle authentication using various providers and a custom backend flow.
-
Install NextAuth.js
If you haven't already, install NextAuth.js:
npm install next-auth
-
Create an API route for NextAuth
In your app directory, create a new file for the authentication API route. This could be located at app/api/auth/[...nextauth]/route.js. This file will configure and export your NextAuth handler.
-
Configure a custom NextAuth provider
Since you have a custom authentication flow, you will need a custom provider. Here is a basic example:
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
const authOptions = {
providers: [
Providers.Credentials({
name: 'Custom Credentials',
credentials: {
phoneNumber: { label: 'Phone Number', type: 'text' },
otp: { label: 'OTP', type: 'text' },
},
authorize: async (credentials) => {
try {
// Step 1: Get a token with the phone number
const tokenResponse = await fetch('https://api.bimehtakmili.com/api/login/generate_token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mobile_no: credentials.phoneNumber }),
});
if (!tokenResponse.ok) {
throw new Error('Failed to generate token');
}
// Step 2: Verify the OTP
const verifyResponse = await fetch('https://api.bimehtakmili.com/api/login/verify_otp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
mobile_no: credentials.phoneNumber,
otp: credentials.otp,
}),
});
if (!verifyResponse.ok) {
throw new Error('Failed to verify OTP');
}
const user = await verifyResponse.json();
// You need to return an object that represents the authenticated user.
return user ? { id: user.id, name: user.name } : null;
} catch (error) {
console.error('Authorization error', error);
return null;
}
},
}),
],
pages: {
signIn: '/auth/signin', // Custom sign-in page
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
-
Create a sign-in page
You need to create a sign-in page that collects the user's phone number and OTP. This can be implemented using a form that submits data to NextAuth.
For example, in app/auth/signin/page.js:
'use client';
import { useState } from 'react';
import { signIn } from 'next-auth/react';
export default function SignIn() {
const [phoneNumber, setPhoneNumber] = useState('');
const [otp, setOtp] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const result = await signIn('credentials', {
redirect: false,
phoneNumber,
otp,
});
// Handle result
if (!result.error) {
// Successful login
window.location.replace('/');
} else {
// Handle error (e.g., display an error message)
console.error(result.error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Phone Number"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
/>
<input
type="text"
placeholder="OTP"
value={otp}
onChange={(e) => setOtp(e.target.value)}
/>
<button type="submit">Sign In</button>
</form>
);
}
-
Use the authentication state
To display user information or manage authentication state across your application, you can use the session hook provided by NextAuth:
import { useSession, signOut } from 'next-auth/react';
function Dashboard() {
const { data: session } = useSession();
if (!session) {
return <div>Not logged in</div>;
}
return (
<div>
<p>Welcome, {session.user.name}!</p>
<button onClick={() => signOut()}>Sign Out</button>
</div>
);
}
This setup allows you to leverage NextAuth's capabilities with your existing authentication backend using phone numbers and OTPs. You may need to adjust error handling and session management based on your specific application needs.