Building User Authentication System with JavaScript

In this lesson, we will use the middleware and cookies to create a user authentication system so that only authenticated users can access certain routes.

User registration

First of all, update the Prisma schema to include a password field.

prisma
1model User {
2  id       Int     @id @default(autoincrement())
3  email    String  @unique
4  name     String
5  password String
6
7  posts Post[]
8}

Apply this new schema by running the following command:

bash
1npx prisma migrate dev

Update the interface for creating new users.

views/user/new.pug

pug
1extends ../layout.pug
2
3block meta
4    name Create New User
5
6block content
7    form(id="newUser")
8        label(for="name") Name:
9        input(type="text", name="name", id="name")
10        br
11        br
12
13        label(for="email") Email:
14        input(type="email", name="email", id="email")
15        br
16        br
17
18        label(for="password") Password:
19        input(type="password", name="password", id="password")
20        br
21        br
22
23        input(type="submit", value="Submit")
24
25    script.
26        . . .
javascript
1document.addEventListener("DOMContentLoaded", function () {
2  const form = document.getElementById("newUser");
3  const nameInput = document.getElementById("name");
4  const emailInput = document.getElementById("email");
5  const passwordInput = document.getElementById("password");
6
7  const formData = new URLSearchParams();
8
9  nameInput.addEventListener("input", function () {
10    formData.set("name", nameInput.value);
11  });
12
13  emailInput.addEventListener("input", function () {
14    formData.set("email", emailInput.value);
15  });
16
17  passwordInput.addEventListener("input", function () {
18    formData.set("password", passwordInput.value);
19  });
20
21  form.addEventListener("submit", async function (event) {
22    event.preventDefault(); // Prevent the default form submission
23
24    await fetch("/users/new", {
25      method: "POST",
26      body: formData.toString(),
27      headers: {
28        "Content-Type": "application/x-www-form-urlencoded",
29      },
30    }).then((data) => (window.location.href = data.url));
31  });
32});

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉