DEV Community

Cover image for Build Modern Stack with Nextjs and NextAuth 5.x with Prisma
Tarun Sharma
Tarun Sharma

Posted on

Build Modern Stack with Nextjs and NextAuth 5.x with Prisma

Introduction

This is what we are building using this modern stack
https://github.com/tkssharma/buddy-clone

This blog post will guide you through creating a modern web application using the powerful combination of Next.js, NextAuth.js 5.x, and Prisma. These tools offer a robust foundation for building scalable, efficient, and secure applications.

Understanding the Stack

  • Next.js: A React framework for building server-rendered or statically generated web applications.
  • NextAuth.js: A library for adding authentication to Next.js applications, supporting various providers like Google, Facebook, GitHub, etc.
  • Prisma: A modern ORM (Object-Relational Mapper) that simplifies database interactions.

Setting Up the Project

  1. Create a New Next.js Project:
   npx create-next-app my-nextjs-app
Enter fullscreen mode Exit fullscreen mode
  1. Install Dependencies:
   cd my-nextjs-app
   npm install next-auth @prisma/client
Enter fullscreen mode Exit fullscreen mode
  1. Configure NextAuth.js: Create a pages/api/auth/[...nextauth].js file and add the following code:
   import NextAuth from 'next-auth';
   import Providers from 'next-auth/providers';

   export default NextAuth({
     providers: [
       Providers.Google({
         clientId: process.env.GOOGLE_CLIENT_ID,
         clientSecret: process.env.GOOGLE_CLIENT_SECRET,
       }),
       // Add other providers as needed
     ],
   });
Enter fullscreen mode Exit fullscreen mode
  1. Set Up Prisma: Create a prisma/schema.prisma file and define your data model:
   model User {
     id        Int      @id @default(autoincrement())
     name      String
     email     String   @unique
     password  String?
   }
Enter fullscreen mode Exit fullscreen mode

Run npx prisma generate to generate Prisma client files.

Integrating NextAuth.js and Prisma

  1. Create a User Service: Create a services/userService.js file and implement user-related functions using Prisma:
   import { PrismaClient } from '@prisma/client';

   const prisma = new PrismaClient();

   export async function createUser(data) {
     const user = await prisma.user.create({ data });
     return user;
   }

   // Implement other functions like getUserByEmail, updateUser, etc.
Enter fullscreen mode Exit fullscreen mode
  1. Use NextAuth.js Callbacks: In pages/api/auth/[...nextauth].js, implement callbacks to handle user sign-up, sign-in, and other authentication-related actions:
   callbacks: {
     async session(session, user) {
       // Update session with additional data from the database
       const sessionUser = await prisma.user.findUnique({ where: { email: user.email } });
       session.user.id = sessionUser.id;
       return session;
     },
     async signIn(user, account, profile) {
       // Handle sign-in logic, e.g., create a new user if needed
       return true;
     },
   },
Enter fullscreen mode Exit fullscreen mode

Building Your Application

  1. Create Pages: Use Next.js's routing system to create pages for different parts of your application, such as home, login, signup, and profile.
  2. Use Context API: Implement context to manage user authentication state across your application.
  3. Fetch Data: Use getStaticProps or getServerSideProps to fetch data from your database and pass it to your components.

Look Into the playlist for getting more on this stack

Conclusion

By combining Next.js, NextAuth.js, and Prisma, you can build modern, scalable, and secure web applications. This powerful stack provides a solid foundation for building your next project.

πŸ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay