🚀
【Next.js】基礎から始めるNext.js API Routes【23Login Form】
【23Login Form】
YouTube: https://youtu.be/JPp3eJ0n0SM
今回はログインフォームを作成します。
前回「[...nextauth].js」の3行目「import prisma from '../../../utils/prismaClient'」
こちらの「prisma」の部分に波かっこが必要でしたので、
まずはこちらの修正から行います。
pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { prisma } from '../../../utils/prismaClient'
export default NextAuth({
providers: [
CredentialsProvider({
name: 'Credentials',
async authorize(credentials) {
const result = await prisma.user.findUnique({
where: {
email: credentials.email,
},
})
if (!result) {
return null
}
if (credentials.password !== result.password) {
throw new Error('Password wrong')
}
return result
},
}),
],
secret: 'secretKey',
session: {
strategy: 'jwt',
},
jwt: {
secret: 'secretKey',
},
callbacks: {
async jwt({ token, user, account, profile, isNewUser }) {
console.log('token :', token)
console.log('user :', user)
console.log('account :', account)
console.log('profile :', profile)
console.log('isNewUser :', isNewUser)
return token
},
async session({ session, token, user }) {
console.log('session :', session)
console.log('token :', token)
console.log('user :', user)
return session
},
},
})
pages/Login.tsx
import Layout from '../components/Layout'
import RegisterForm from '../components/RegisterForm'
export default function LoginPage() {
return (
<Layout>
<div className="flex flex-col justify-center items-center">
<h2 className="text-4xl font-black font-sans p-4 mt-6">Login Form</h2>
<RegisterForm />
</div>
</Layout>
)
}
components/LoginForm.tsx
import { Button, Label, TextInput } from 'flowbite-react'
import { ChangeEvent, SyntheticEvent, useState } from 'react'
const LoginForm = () => {
const [formData, setFormData] = useState({
email: '',
password: '',
})
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const { value, name } = e.target
setFormData({ ...formData, [name]: value })
}
const handleSubmit = async (e: SyntheticEvent) => {
e.preventDefault()
const res = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
if (res.status === 200) {
const user = await res.json()
console.log(user)
} else {
console.log(`${res.status} something went wrong`)
}
// alert(JSON.stringify(formData))
}
return (
<div className="w-60">
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<div>
<div className="mb-2 block">
<Label htmlFor="email1" value="Your email" />
</div>
<TextInput
id="email1"
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required={true}
/>
</div>
<div>
<div className="mb-2 block">
<Label htmlFor="password1" value="Your password" />
</div>
<TextInput
id="password1"
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required={true}
/>
</div>
<Button type="submit">Login</Button>
</form>
</div>
)
}
export default LoginForm
Discussion