Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 호이스팅
- toast-ui-editor
- 모던 자바스크립티 Deep Dive
- Weekly Contest
- sql
- leetcode
- engines locking
- React
- BFS
- javascript
- Vite
- next.js
- next-auth
- commitlint
- 모던 자바스크립트 Deep Dive
- LV. 2
- 프로그래머스
- Sanity.io
- React Router dom v6
- medinum
- Medium
- .env
- react-dom
- eslintrc
- 컴포넌트 최적화
- Biweekly Contest 79
- tailwindcss
- React Private Routes
- React.memo
- React Public Routes
Archives
- Today
- Total
뚜벅
NextAuth + Prisma + MongoDB 사용 방법 본문
이번 개인 프로젝트에서 prisma + mongoDB 를 사용하게 돼서 사용하는 방법에 관해 글을 작성합니다.
1. MongoDB Atlas Database 생성
1. 사이트 접속 후 로그인
2. Project 생성
project 이름과 추가할 멤버를 설정한 뒤 project를 생성합니다.
3. Database 생성
저는 무료버전을 사용해서 database를 생성했습니다!
비밀번호는 중요하니깐 따로 복사해서 저장해 줍니다.!
조금만 기다리면..!! 메인에 생성된 database가 보입니다
하지만 Browse Collections를 클릭해서 보면 생성한 Collections이 없어서
아무것도 보이지 않습니다.
이제 프로젝트에 prisma를 설치하고 스키마를 작성해 보겠습니다.
2. Prisma 설정
prisma 설치 및 초기 세팅
yarn add -D prisma
yarn add @prisma/client
npx prisma
npx prisma init // .env 파일, prisma/schema.prisma 파일 생성
1. 생성된 .env 파일에서 DATEBASE_URL을 규칙에 맞게 작성해 줍니다.
여기를 클릭하면
2. 스키마 작성
next-auth 기본 예제를 사용했습니다.
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model Account {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String @db.ObjectId
type String
provider String
providerAccountId String @map("provider_account_id")
refresh_token String? @db.String
access_token String? @db.String
expires_at Int?
token_type String?
scope String?
id_token String? @db.String
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
@@map("accounts")
}
model Session {
id String @id @default(auto()) @map("_id") @db.ObjectId
sessionToken String @unique @map("session_token")
userId String @db.ObjectId
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("sessions")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String?
email String? @unique
emailVerified DateTime? @map("email_verified")
image String?
accounts Account[]
sessions Session[]
@@map("users")
}
model VerificationToken {
id String @id @default(auto()) @map("_id") @db.ObjectId
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
3. lib/prismadb.ts 파일 생성
import { PrismaClient } from '@prisma/client';
declare global {
var prisma: PrismaClient | undefined;
}
const client = global.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') global.prisma = client;
export default client;
3. Next-Auth 설치 및 세팅
yarn add next-auth @next-auth/prisma-adapter
1. pages/api/auth/[...nextauth].ts 파일 생성
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import KakaoProvider from 'next-auth/providers/kakao';
import GoogleProvider from 'next-auth/providers/google';
import prisma from '../../../lib/prismadb';
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID!,
clientSecret: process.env.GOOGLE_SECRET!,
}),
],
});
2.pages/_app.tsx 파일에 SessionProvider 추가
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
3. login button 추가 및 로그인!!
import Head from "next/head";
import Image from "next/image";
import { Inter } from "next/font/google";
import styles from "@/styles/Home.module.css";
import { signIn } from "next-auth/react";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<button onClick={() => signIn("google")}>login</button>
</main>
</>
);
}
이제 prisma studo와 mongodb collections를 확인하면 데이터를 확인할 수 있습니다
npx prisma studio
'Next.js' 카테고리의 다른 글
Next.js 프로젝트 세팅 (0) | 2023.03.13 |
---|---|
[postcss] Cannot read properties of undefined (reading 'config') 에러 해결 (0) | 2023.01.27 |
Parsing Error: Cannot find module '@babel/preset-env' for Sanity (0) | 2022.11.20 |