#how to use next-auth typescript with my nextjs project with a custom login page
1 messages · Page 1 of 1 (latest)
To use NextAuth with TypeScript in your Next.js project, you need to set up a specific route for authentication and configure NextAuth.js with your GitHub OAuth credentials and the Prisma adapter. Here's how you can do it:
- Create a new directory and a new file in the
pages/apidirectory:
mkdir -p pages/api/auth && touch pages/api/auth/[...nextauth].ts
- In the new
pages/api/auth/[...nextauth].tsfile, add the following boilerplate to configure your NextAuth.js setup with your GitHub OAuth credentials and the Prisma adapter:
import { NextApiHandler } from 'next';
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import GitHubProvider from 'next-auth/providers/github';
import prisma from '../../../lib/prisma';
const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;
const options = {
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.SECRET,
};
- If you have a custom
App, you can use the built-in typeAppPropsand change the file name to./pages/_app.tsx:
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
- For the custom login page, you can use the
loginWithMagicLinkfunction from Magic to handle the login process. Here's an example of how you can do it:
import { useContext, useState, useEffect } from 'react';
import { UserContext } from '@/lib/UserContext';
import { useRouter } from 'next/router';
import { magic } from '@/lib/magic';
export default function Login() {
const [user, setUser] = useContext(UserContext);
const [email, setEmail] = useState('');
const router = useRouter();
useEffect(() => {
user?.issuer && router.push('/dashboard');
}, [user]);
const handleLogin = async (e) => {
e.preventDefault();
try {
const didToken = await magic.auth.loginWithMagicLink({ email, });
const res = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-type': 'application/json',
Authorization: `Bearer ${didToken}`,
},
});
} catch (error) {
console.error(error);
}
};
return (
<form onSubmit={handleLogin}>
<label htmlFor="email">Email</label>
<input name="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Send Magic Link</button>
</form>
);
}
Please note that you need to replace `'@/lib/UserContext'` and `'@/lib/magic'` with the actual paths to your UserContext and Magic libraries.
Sources:
- **Vercel Guide** (<https://vercel.com/guides/nextjs-prisma-postgres>)
- **Next.js Documentation** (<https://nextjs.org/docs/pages/building-your-application/configuring/typescript>)
- **Vercel Guide** (<https://vercel.com/guides/add-auth-to-nextjs-with-magic>)
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
@tall bloom kapa.ai is still learning and improving, please let us know how it did by reacting below
do u support nextjs 13?
next-auth support nextjs 13.