728x90
๋ฐ์ํ
๐ก Next Auth JWT, Session ์ฌ์ฉ ์ ์ฌ์ฉ์ ์ ์ ์์ฑ(์: role)์ auth(session)์์ ์ถ๊ฐํ๊ณ User | AdapterUser ํ์ ์ค์ ์ ํ๋ ๋ฐฉ๋ฒ์ผ๋ก ํ์ ์๋ฌ๋ฅผ ์ ๊ฑฐํ๊ณ ์ํ๋ ์์ฑ์ ์ฌ์ฉํ ์ ์๊ฒ ์ค์ ํ๋ค.
type.d.ts ์ค์
ํ๋ก์ ํธ ๋ฃจํธ ํด๋์ type.d.ts ํ์ผ ์์ฑ ํ ์๋์ ๊ฐ์ด ์ ๋ ฅ ํ tsconfig.json์ ๋ฑ๋ก
//type.d.ts
import { JWT } from 'next-auth/jwt';
import NextAuth, { type DefaultSession } from 'next-auth';
declare module 'next-auth/jwt' {
interface JWT {
//JWT์์ ์ฌ์ฉํ ์ฌ์ฉ์ ์ ์ ์์ฑ ๋ฑ๋ก
role: string;
}
}
declare module 'next-auth' {
export interface User extends DefaultUser {
//User | AdapterUser์์ ์ฌ์ฉํ ์ฌ์ฉ์ ์ ์ ์์ฑ ๋ฑ๋ก
role: string;
}
interface Session {
user: {
//Session์์ ์ฌ์ฉํ ์ฌ์ฉ์ ์ ์ ์์ฑ ๋ฑ๋ก
role: string;
} & DefaultSession['user'];
}
}
//tsconfig.json
{
//compilerOptions...
//paths...
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"app/lib/placeholder-data.js",
"scripts/seed.js",
"type.d.ts" // <--- ๋ฑ๋ก
],
//exclude...
}
์ฌ์ฉ์ ์ ์ ํ์ ์ ์ธ ์ next-env.d.ts๋ฅผ ์ฌ์ฉํ๋ฉด ์๋ฉ๋๋ค. ์ด ํ์ผ์ ์๋์ผ๋ก ์์ฑ๋๋ฏ๋ก ๋ณ๊ฒฝ๋ ๋ด์ฉ์ ๋ฎ์ด์ฐ์ฌ์ง๊ธฐ ๋๋ฌธ์ ์ ํ์ผ์ ๋ง๋ค๊ณ tsconfig.json์์ ์ฐธ์กฐํด์ผ ํฉ๋๋ค.
์ฌ์ฉ
export async function getUserOne(): Promise<User> {
const session = await auth();
console.log(session.user.id);
console.log(session.user.role);
}
export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isAdmin = auth.user.role
const isAdminRoute = adminRoute.includes(nextUrl.pathname);
//...
},
},
} satisfies NextAuthConfig;
Auth.js | Typescript
Authentication for the Web
authjs.dev
Configuring: TypeScript | Next.js
Next.js provides a TypeScript-first development experience for building your React application.
nextjs.org
728x90
๋ฐ์ํ