created at 2023/08/05 03:01:01
updated at 2023/08/05 05:03:16
app/api/auth/[...nextauth]/options.ts
typescript
import type { NextAuthOptions } from 'next-auth';
import GitHubProvider from 'next-auth/providers/github';
export const options: NextAuthOptions = {
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID as string,
clientSecret: process.env.GITHUB_SECRET as string,
}),
],
};
app/api/auth/[...nextauth]/route.ts
typescript
import NextAuth from 'next-auth';
import { options } from './options';
const handler = NextAuth(options);
export { handler as GET, handler as POST };
AuthProvider
tsx
'use client';
import { SessionProvider } from 'next-auth/react';
export default function AuthProvider({
children,
}: {
children: React.ReactNode;
}) {
return <SessionProvider>{children}</SessionProvider>;
}
tsx
'use client';
// Remember you must use an AuthProvider for
// client components to useSession
import { useSession } from 'next-auth/react';
import { redirect } from 'next/navigation';
export default function ClientPage() {
const { data: session } = useSession({
required: true,
onUnauthenticated() {
redirect('/api/auth/signin?callbackUrl=/client');
},
});
return <></>;
}
tsx
import { options } from '../api/auth/[...nextauth]/options';
import { getServerSession } from 'next-auth/next';
import { redirect } from 'next/navigation';
export default async function ServerPage() {
const session = await getServerSession(options);
if (!session) {
redirect('/api/auth/signin?callbackUrl=/server');
}
return <></>;
}
ts
// Without a defined matcher, this one line applies next-auth
// to the entire project
export { default } from 'next-auth/middleware';
// Applies next-auth only to matching routes - can be regex
// Ref: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = { matcher: ['/extra', '/dashboard'] };