Skip to content

SignUp

Allows users to register in your application using their credentials.

Signup Page

Start by creating a new page, then create a form and add the necessary input fields.

src/app/pages/signup.ts
import SignUp from "@/src/actions/auth"
export default function Page() {
return (
<div>
<h1>Create account</h1>
<form action={SignUp}>
<label htmlFor="username">username</label>
<input type="text" name="username" id="username" />
<br />
<label htmlFor="password">password</label>
<input type="text" name="password" id="password" />
<br />
<button type="submit">Submit</button>
</form>
</div>
)
}

Handle Signup

Within the form action, get and validate the user credentials, if its valid, hash the password and insert them into the database, Then, either redirect the user to the sign-in page or, create a session using createSession, set the session cookie, and redirect the user to the protected route.

It is recommended to validate the user credentials client-side and server-side before proceeding.

You can also use useActionState to return a value and display a message to the user.

src/actions/auth.ts
"use server"
import { cookies } from "next/headers"
import bcrypt from "bcrypt"
import { redirect } from "next/navigation"
import { createSession } from "@/auth"
export async function SignIn(formData: FromData) {
// USER CREDENTIALS
const credentials = {
username: formData.get("username") as string,
password: formData.get("password") as string
}
// VALIDATE USER CREDENTIALS, USERNAME AND PASSWORD
// HASH THE PASSWORD
const hash_password = bcrypt.hash(credentials.password, 10)
// INSERT USER INTO DB
await db.users.insert({
data: {
username: credentials.username,
hash_password
}
})
const sessionCookie = await createSession((sessionToken) => {
const sessionToken.session.name = user.name
const sessionToken.session.email = user.email
return sessionToken
})
cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.options)
redirect("/dashboard")
}