@wekeepgrowing/auth-next
v0.1.12
Published
Headless authentication library for wekeepgrowing
Downloads
31
Maintainers
Readme
Next.js 인증 모듈
Next.js 프로젝트에서 인증 기능을 쉽게 통합할 수 있는 헤드리스 인증 라이브러리입니다.
설치
npm install @wekeepgrowing/auth-next특징
- Next.js 미들웨어를 통한 자동 인증 API 라우팅
- 토큰 기반 인증 (액세스 토큰 및 리프레시 토큰)
- 매직 코드 및 비밀번호 로그인 지원
- 자동 토큰 갱신
- React 컨텍스트 API를 통한 인증 상태 관리
- TypeScript 지원
- DUID(장치 식별자) 자동 관리
서버 측 설정
Next.js 미들웨어에서 사용
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { AuthMiddleware } from '@wekeepgrowing/auth-next/server';
const authMiddleware = new AuthMiddleware({
baseUrl: process.env.AUTH_API_URL || 'https://api.example.com',
basePath: '/api/auth'
});
export async function middleware(request: NextRequest) {
// 인증 관련 요청 처리
const response = await authMiddleware.handle(request);
if (response) return response;
// 다른 미들웨어 로직...
return NextResponse.next();
}
// 인증 API 경로에 대해서만 미들웨어 실행
export const config = {
matcher: ['/api/auth/:path*']
};클라이언트 측 설정
AuthProvider 설정
// _app.tsx 또는 layout.tsx
import { AuthProvider } from '@wekeepgrowing/auth-next';
function MyApp({ Component, pageProps }) {
return (
<AuthProvider apiBasePath="/api/auth">
<Component {...pageProps} />
</AuthProvider>
);
}
export default MyApp;인증 훅 사용하기
import { useAuth } from '@wekeepgrowing/auth-next';
function LoginPage() {
const { login, isLoading, isAuthenticated } = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(email, password);
// 로그인 성공 처리
} catch (error) {
// 오류 처리
console.error('로그인 실패:', error);
}
};
if (isAuthenticated) {
// 이미 로그인된 경우 리디렉션 등의 처리
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="이메일"
required
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="비밀번호"
required
/>
<button type="submit" disabled={isLoading}>
{isLoading ? '로그인 중...' : '로그인'}
</button>
</form>
);
}매직 코드 로그인 예제
import { useAuth } from '@wekeepgrowing/auth-next';
function MagicCodeLogin() {
const { requestMagicCode, loginWithMagicCode, isLoading } = useAuth();
const [email, setEmail] = useState('');
const [code, setCode] = useState('');
const [codeSent, setCodeSent] = useState(false);
const handleRequestCode = async (e) => {
e.preventDefault();
try {
await requestMagicCode(email);
setCodeSent(true);
} catch (error) {
console.error('매직 코드 요청 실패:', error);
}
};
const handleSubmitCode = async (e) => {
e.preventDefault();
try {
await loginWithMagicCode(email, code);
// 로그인 성공 처리
} catch (error) {
console.error('매직 코드 로그인 실패:', error);
}
};
if (!codeSent) {
return (
<form onSubmit={handleRequestCode}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="이메일"
required
/>
<button type="submit" disabled={isLoading}>
코드 요청
</button>
</form>
);
}
return (
<form onSubmit={handleSubmitCode}>
<input
type="text"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="인증 코드"
required
/>
<button type="submit" disabled={isLoading}>
로그인
</button>
</form>
);
}사용자 등록 예제
import { useAuth } from '@wekeepgrowing/auth-next';
function RegisterPage() {
const { register, isLoading } = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [username, setUsername] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await register(email, password, username);
// 등록 성공 처리
} catch (error) {
console.error('등록 실패:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="이메일"
required
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="비밀번호"
required
/>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="사용자 이름 (선택사항)"
/>
<button type="submit" disabled={isLoading}>
{isLoading ? '등록 중...' : '회원가입'}
</button>
</form>
);
}로그아웃 예제
import { useAuth } from '@wekeepgrowing/auth-next';
function LogoutButton() {
const { logout, isLoading } = useAuth();
const handleLogout = async () => {
try {
await logout();
// 로그아웃 후 처리
} catch (error) {
console.error('로그아웃 실패:', error);
}
};
return (
<button onClick={handleLogout} disabled={isLoading}>
{isLoading ? '로그아웃 중...' : '로그아웃'}
</button>
);
}인증 상태 확인
import { useAuth } from '@wekeepgrowing/auth-next';
function ProfilePage() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return <div>로딩 중...</div>;
}
if (!isAuthenticated) {
return <div>로그인이 필요합니다.</div>;
}
return (
<div>
<h1>프로필</h1>
<p>사용자 ID: {user?.id}</p>
<p>이메일: {user?.email}</p>
<p>이름: {user?.name || '이름 없음'}</p>
</div>
);
}환경변수 설정
# .env.local
AUTH_API_URL=https://api.example.com라이선스
이 라이브러리는 내부 사용 전용입니다.
