Casual Clothes App Using Next.js 14, TypeScript, Prisma & Next-Auth

WHAT TO KNOW - Sep 1 - - Dev Community

<!DOCTYPE html>





Building a Casual Clothes App with Next.js 14, TypeScript, Prisma, and Next-Auth

<br> body {<br> font-family: sans-serif;<br> margin: 0;<br> padding: 0;<br> background-color: #f8f8f8;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code> h1, h2, h3 { color: #333; } code { background-color: #eee; padding: 2px 5px; font-family: monospace; } pre { background-color: #eee; padding: 10px; overflow-x: auto; } img { max-width: 100%; height: auto; } </code></pre></div> <p>



Building a Casual Clothes App with Next.js 14, TypeScript, Prisma, and Next-Auth



This article guides you through building a full-fledged casual clothes app using a combination of cutting-edge technologies: Next.js 14, TypeScript, Prisma, and Next-Auth. This comprehensive guide will cover setting up the project, implementing core features, styling the app, and deploying it.



Introduction



In the ever-evolving world of web development, building dynamic and engaging web applications is paramount. Next.js, with its server-side rendering, static site generation, and robust features, stands out as a powerful framework for creating modern web apps. Combining it with TypeScript for type safety, Prisma for seamless database interaction, and Next-Auth for effortless authentication, we have all the tools to create a robust and user-friendly casual clothes app.



Why Choose These Technologies?

  • Next.js 14: Next.js 14 provides a streamlined development experience, exceptional performance through server-side rendering and static site generation, and an intuitive API route system for building backend logic.
    • TypeScript: TypeScript brings type safety to JavaScript, catching errors early in development, improving code maintainability, and increasing overall code quality.
    • Prisma: Prisma simplifies database interaction, eliminating boilerplate code and providing a type-safe way to interact with your database, ensuring data consistency and reducing errors.
    • Next-Auth: Next-Auth offers a flexible and secure authentication solution for Next.js applications, seamlessly integrating with various providers like Google, Facebook, and GitHub.

      Project Setup

      Let's get started by setting up the project. We'll use the Next.js create app command, which includes TypeScript support by default.

    • Install Node.js and npm

      Make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download the latest version from the official Node.js website ( https://nodejs.org/ ). After installation, verify the installation by running node -v and npm -v in your terminal.

    • Create the Next.js App
npm create next-app@latest my-casual-clothes-app --ts


This command creates a new Next.js project named my-casual-clothes-app with TypeScript enabled. Navigate into the project directory:


cd my-casual-clothes-app

  1. Initialize the Project

npm install


This command installs all the necessary dependencies from the package.json file.



Setting Up Prisma



Next, we'll integrate Prisma into our project to manage the database interactions.


  1. Install Prisma

npm install --save-dev prisma

  1. Create a Prisma Schema

Create a file named prisma/schema.prisma in your project root directory and add the following code:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(auto()) @map("_id") @db.AutoIncrement()
  email     String   @db.VarChar(255) @unique
  password  String   @db.VarChar(255)
  name      String?  @db.VarChar(255)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  // Relation to Clothing Items
  clothingItems ClothingItem[] 
}

model ClothingItem {
  id        Int      @id @default(auto()) @map("_id") @db.AutoIncrement()
  name      String   @db.VarChar(255)
  imageUrl  String?  @db.VarChar(255)
  category  String   @db.VarChar(255)
  price     Float    @db.Decimal(10, 2)
  description String?  @db.Text
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  // Relation to User
  owner     User     @relation(fields: [ownerId], references: [id])
  ownerId   Int
}


This schema defines our database structure:

  • User: Represents users of the app. It stores user details like email, password, name, and timestamps for creation and update.
    • ClothingItem: Represents individual clothing items. It stores the item name, image URL, category, price, description, and relationships with the user (owner) who added it.

    • Initialize Prisma
npx prisma init


This creates the prisma directory containing a .env file and other configuration files.


  1. Generate Prisma Client

npx prisma generate


This generates the Prisma Client, which provides type-safe functions for interacting with your database.


  1. Set Up the Database

You'll need a PostgreSQL database to connect with. You can use a cloud service like Heroku Postgres or set up a local PostgreSQL instance. Once you have your database set up, update the DATABASE_URL in the .env file.

DATABASE_URL=postgres://your_username:your_password@your_host:your_port/your_database_name


Now, run the following to seed your database with some initial data:


npx prisma db push


Implementing Authentication with Next-Auth



Next-Auth makes authentication a breeze. We'll use it to allow users to sign in and access their personal data.


  1. Install Next-Auth

npm install next-auth 

  1. Configure Next-Auth

Create a file called pages/api/auth/[...nextauth].js in your pages directory.

import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'email', placeholder: 'john.doe@example.com' },
        password: { label: 'Password', type: 'password' }
      },
      async authorize(credentials, req) {
        const user = await prisma.user.findUnique({
          where: { email: credentials.email },
        })

        if (!user || !user.password || user.password !== credentials.password) {
          return null
        }

        return { id: user.id, email: user.email, name: user.name }
      },
    }),
  ],
  pages: {
    signIn: '/login', 
  },
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async session({ session, token }) {
      const user = await prisma.user.findUnique({
        where: { id: session.user.id },
      });

      // Add clothingItems to the session object
      if (user) {
        const clothingItems = await prisma.clothingItem.findMany({
          where: { ownerId: user.id },
        });
        session.user.clothingItems = clothingItems;
      }

      return session;
    },
  },
})


This code sets up Next-Auth for:

  • Authentication Provider: We're using the CredentialsProvider for user authentication with email and password.
    • Database Adapter: PrismaAdapter integrates Next-Auth with our Prisma database.
    • Sign-In Page: Redirects users to the /login page for sign-in.
    • Secret: Replace process.env.NEXTAUTH_SECRET with a secret key generated for your application.
    • Session Callback: This retrieves the user's clothing items from the database and adds them to the session object.

      Creating Clothing Item Pages

      Now, let's start creating pages for viewing and managing clothing items.

    • Create a New Page

      Create a new file named pages/clothingItems/[id].tsx for displaying individual clothing items.

'use client'
import React from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function ClothingItemPage({ params }) {
  const { data: session } = useSession();
  const router = useRouter();
  const itemId = params.id;

  const clothingItem = await prisma.clothingItem.findUnique({
    where: { id: parseInt(itemId, 10) },
    include: {
      owner: true,
    },
  });

  if (!clothingItem) {
    return
  <p>
   Clothing item not found.
  </p>
  ;
  }

  if (session &amp;&amp; session.user.id === clothingItem.ownerId) {
    return (
  <div>
   <h2>
    {clothingItem.name}
   </h2>
   <img alt="{clothingItem.name}" src="{clothingItem.imageUrl}"/>
   <p>
    Category: {clothingItem.category}
   </p>
   <p>
    Price: ${clothingItem.price}
   </p>
   <p>
    Description: {clothingItem.description}
   </p>
   {/* Add more details and actions here */}
  </div>
  );
  } else {
    return (
  <div>
   <p>
    You do not have access to this clothing item.
   </p>
   <button =="" onclick="{()">
    router.push('/clothingItems')}&gt;
          Back to Clothing Items
   </button>
  </div>
  );
  }
}


This page fetches a clothing item by its ID from the database, displays its details, and only allows the owner to view and edit it. The useSession hook from Next-Auth is used to check user authentication.


  1. Create a Listing Page

Create a new file named pages/clothingItems.tsx for listing all clothing items.

'use client'
import React from 'react';
import { useSession } from 'next-auth/react';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function ClothingItemsPage() {
  const { data: session } = useSession();

  const clothingItems = await prisma.clothingItem.findMany({
    where: {
      ownerId: session?.user.id, // Filter by current user's ID if logged in
    },
  });

  return (
  <div>
   <h1>
    Clothing Items
   </h1>
   <ul>
    {clothingItems.map((item) =&gt; (
    <li key="{item.id}">
     <a href="{`/clothingItems/${item.id}`}">
      {item.name}
     </a>
    </li>
    ))}
   </ul>
  </div>
  );
}


This page retrieves all clothing items associated with the logged-in user and renders them in a list. You can customize the styling and add functionality like sorting, filtering, and adding new items.



Adding New Clothing Items



Next, let's add a form to allow users to create new clothing items.


  1. Create a New Clothing Item Form

Create a new file named pages/newClothingItem.tsx.

'use client'
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default function NewClothingItemPage() {
  const { data: session } = useSession();
  const router = useRouter();
  const [name, setName] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [category, setCategory] = useState('');
  const [price, setPrice] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = async (event) =&gt; {
    event.preventDefault();

    try {
      await prisma.clothingItem.create({
        data: {
          name,
          imageUrl,
          category,
          price: parseFloat(price),
          description,
          ownerId: session.user.id,
        },
      });

      router.push('/clothingItems');
    } catch (error) {
      console.error('Error creating clothing item:', error);
    }
  };

  return (
  <form onsubmit="{handleSubmit}">
   <h2>
    Add New Clothing Item
   </h2>
   <div>
    <label htmlfor="name">
     Name:
    </label>
    <input =="" id="name" onchange="{(e)" type="text" value="{name}"/>
    setName(e.target.value)}
        /&gt;
   </div>
   {/* Add input fields for imageUrl, category, price, and description */}
   <button type="submit">
    Create Item
   </button>
  </form>
  );
}


This page includes a form that allows users to enter details for their new clothing item. The handleSubmit function sends the data to the database using Prisma. Once the item is created, the user is redirected to the clothingItems page.



Styling the App



You can use your preferred styling solution to enhance the visual appearance of your app. Here are a few popular options:

  • CSS Modules: For scoped CSS.
    • Tailwind CSS: A utility-first CSS framework.
    • Styled Components: For writing CSS in JavaScript.

      Example using Tailwind CSS

      Install Tailwind CSS and its dependencies:

npm install -D tailwindcss postcss autoprefixer


Create a tailwind.config.js file in your project root:


/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
    './app/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}


Add Tailwind directives to your pages/_app.tsx file:


import '../styles/globals.css'
import 'tailwindcss/tailwind.css'

export default function App({ Component, pageProps }) {
  return
  <component {...pageprops}="">
  </component>
  }


Now, you can use Tailwind CSS classes directly in your components for styling. For example, you can add the following to the clothingItems.tsx page:


  <div classname="container mx-auto p-4">
   <h1 classname="text-3xl font-bold mb-4">
    Clothing Items
   </h1>
   <ul classname="list-disc">
    {/* ... */}
   </ul>
  </div>


Deployment



Deploying your Next.js app is straightforward with platforms like Vercel, Netlify, or AWS.



Vercel Deployment



Vercel is the official deployment platform for Next.js.

  • Sign up for a Vercel account: https://vercel.com/
  • Install the Vercel CLI: npm install -g vercel
    • Log in to Vercel: vercel login
    • Initialize your project for deployment: vercel init
    • Deploy your app: vercel

      Netlify Deployment

      Netlify is another popular platform for deploying static websites and Next.js applications.

  • Sign up for a Netlify account:
    https://www.netlify.com/
  • Install the Netlify CLI: npm install -g netlify-cli
    • Log in to Netlify: netlify login
    • Create a new Netlify site: netlify init
    • Deploy your app: netlify deploy

      Conclusion

      Congratulations! You've successfully built a casual clothes app using Next.js 14, TypeScript, Prisma, and Next-Auth. This robust combination of technologies provides a powerful foundation for building modern web applications. Here are some key takeaways:

  • Next.js: Provides a fast and efficient framework for server-side rendering, static site generation, and API routes.
    • TypeScript: Enhances code quality and maintainability with type safety.
    • Prisma: Simplifies database interaction, ensuring data consistency and reducing errors.
    • Next-Auth: Offers a secure and flexible authentication solution for your app.

      Remember to continuously learn and explore new features as the web development landscape evolves. This guide provides a starting point for building your own dynamic and interactive web applications.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player