728x90
pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
secret: "qwer1234",
};
export default NextAuth(authOptions);
로그인버튼과 로그아웃버튼을 만들었다.
LoginBtn.js
"use client";
import { signIn } from "next-auth/react";
export default function LoginBtn() {
return (
<button
onClick={() => {
signIn();
}}
>
로그인
</button>
);
}
LogoutBtn.js
"use client";
import { signOut } from "next-auth/react";
export default function LogoutBtn() {
return (
<button
onClick={() => {
signOut();
}}
>
로그아웃
</button>
);
}
layout.js
//page.js를 감싸는 파일이다.
//보통 Head내용을 여기에 쓴다.
import { Inter } from "next/font/google";
import "./globals.css";
import Link from "next/link";
import LoginBtn from "./LoginBtn";
import LogoutBtn from "./LogoutBtn";
import { getServerSession } from "next-auth";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default async function RootLayout({ children }) {
let session = await getServerSession(authOptions);
// console.log(session);
return (
<html lang="en">
<body className={inter.className}>
<div className="navbar">
<Link href="/">홈</Link>
<Link href="/list">List</Link>
<Link href="/cart">Cart</Link>
<Link href="/about">About</Link>
{session ? (
<span>
{session.user.name}
<LogoutBtn />
</span>
) : (
<LoginBtn />
)}
</div>
{children}
</body>
</html>
);
}
로그인이 된 유저정보 출력은 getServerSession을 이용하면 된다.
getServerSession은 서버컴포넌트, 서버기능안에서 사용가능하다.
그리고 await과 함께 사용해야한다.
oauth정보를 출력해보면 이런식으로 출력이 될거다.
{
user: {
name: 'ddddd',
email: 'dddddd@gmail.com',
image: 'abcdddddd'
}
}
그걸 이용해서 삼항연산자 이용해서 로그인버튼과 로그아웃버튼 번갈아가며 뜨게하면된다.
728x90
'교육후 개인공부 > React' 카테고리의 다른 글
[Next.js] dynamic route와 id맞추기(상세페이지설정) (0) | 2024.02.20 |
---|---|
mongoDb 연결하기 (0) | 2024.02.20 |
[Next.js] 게시물수정하기 (0) | 2023.12.07 |
[Next.js] mongodb에 데이터 삽입하기 (1) | 2023.12.07 |
[React] todolist 구현완성본 (1) | 2023.12.06 |