DEV Community

Yash Mehta
Yash Mehta

Posted on

Streamlining User Authentication with Next.js 14 and Next-Auth

Introduction:

In the ever-evolving landscape of web development, creating a secure and seamless authentication system is crucial for any modern website. With the release of Next.js 14 and the power of Next-Auth, implementing robust login and registration functionality has become more straightforward than ever. In this blog post, we'll guide you through the process of setting up authentication for your Next.js application using Next-Auth.

Prerequisites: Before we dive into the implementation, make sure you have Node.js installed on your machine and a basic understanding of Next.js.

Step 1: Create a Next.js App

If you haven't already set up a Next.js app, start by creating one using the following commands:

npx create-next-app my-next-auth-app
cd my-next-auth-app
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Next-Auth

Next, install the Next-Auth package by running:

npm install next-auth
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Next-Auth

Create a pages/api/auth/[...nextauth].js file in your project and configure Next-Auth. Here's a simple example:

// pages/api/auth/[...nextauth].js
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: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text' },
        password: {  label: 'Password',  type: 'password' },
      },
      async authorize(credentials, req) {
        // Add custom authentication logic here
        const user = { id: 1, name: 'example' };
        if (user) {
          return Promise.resolve(user);
        } else {
          return Promise.resolve(null);
        }
      },
    }),
    // Add other providers as needed
  ],
  // Add other global options here
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Implement Login and Registration Components

Create components for login and registration in the components directory. Use the useSession hook from Next-Auth to manage the user's session.

// components/LoginForm.js
import { useState } from 'react';
import { signIn } from 'next-auth/react';

const LoginForm = () => {
  const [credentials, setCredentials] = useState({});

  const handleSubmit = (e) => {
    e.preventDefault();
    signIn('credentials', { ...credentials, redirect: false });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Username"
        onChange={(e) => setCredentials({ ...credentials, username: e.target.value })}
      />
      <input
        type="password"
        placeholder="Password"
        onChange={(e) => setCredentials({ ...credentials, password: e.target.value })}
      />
      <button type="submit">Sign In</button>
    </form>
  );
};

export default LoginForm;
Enter fullscreen mode Exit fullscreen mode

Step 5: Integrate Authentication in Your Pages

Update your pages to include the authentication components.

// pages/index.js
import { useSession } from 'next-auth/react';
import LoginForm from '../components/LoginForm';

const Home = () => {
  const { data: session } = useSession();

  return (
    <div>
      {session ? (
        <p>Welcome, {session.user.name}!</p>
      ) : (
        <LoginForm />
      )}
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Step 6: Start Your Next.js App

Run your Next.js app with the following command:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 and witness the magic of Next-Auth in action. Users can now register, log in, and enjoy a personalized experience on your Next.js website.

Conclusion:

Implementing user authentication with Next.js 14 and Next-Auth is a breeze, offering a secure and customizable solution for your web applications. Feel free to explore more authentication providers and customize the user experience based on your specific requirements. Happy coding!

Top comments (0)