Skip to content

Writing the frontend for it

Course: Authentication - chapter 11

Until now, we’ve been using POSTMAN to send out all of our requests.

Now, lets create a full stack application. Lets write the frontend that lets you

  1. Signup
  2. Signin
  3. Get your information
  4. Logout
Create a `public/index.html` file
mkdir public
cd public
touch index.html
Create a `signup section`
<div>
Signup
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button onclick="signup()">Submit</button>
</div>
Create a `signin section`
<div>
Signin
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button onclick="signin()">Submit</button>
</div>
Create a `User information` section
<div>
User information:
<div id="information"></div>
</div>
Create a logout button
<div>
<button onclick="logout()">Logout</button>
</div>
Add the axios external library
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.7.7/axios.min.js"></script>
Write the signup function
async function signup() {
const username = document.getElementById("signup-username").value;
const password = document.getElementById("signup-password").value;
const response = await axios.post("http://localhost:3000/signup", {
username: username,
password: password
})
alert("Signed up successfully");
}
Write the signin function
async function signin() {
const username = document.getElementById("signin-username").value;
const password = document.getElementById("signin-password").value;
const response = await axios.post("http://localhost:3000/signin", {
username: username,
password: password
});
localStorage.setItem("token", response.data.token);
alert("Signed in successfully");
}
Write the logout function
async function logout() {
localStorage.removeItem("token");
}
Write the `getUserInformation` function
async function getUserInformation() {
const token = localStorage.getItem("token");
if (token) {
const response = await axios.get("http://localhost:3000/me", {
headers: {
Authorization: token
}
});
document.getElementById("information").innerHTML = response.data.username;
}
}

Lets serve the index.html file directly from the backend

Approach #1
app.get("/", function(req, res) {
res.sendFile("./public/index.html")
})
Approach #2
app.use(express.static("./public"))

Call the `getUserInformation` function when the page loads
getUserInformation();

Conditionally render the logout or the signin/ signup pages based on if the user is already logged in or not