How to build login form with firebase in Next.js

Cover Image for How to build login form with firebase in Next.js
Ali Bentaleb

Login form is very important for our apps so we can know who is logged into our app and which profile should it have so the appropriate rights can be given to the signed in user

In this tutorial, we will going to show how to build a login form using Next.js and tailwindcss, and firebase as backend for validating the user login.

Install Next.js, tailwindcss and firebase

You need first to have a Next.js project, if you don’t already have it you can check my link for installation, or use these commands for a quick setup

Create a folder and navigate to it, then run

npx create-next-app@latest my-app

Next, we are going to install tailwind which is a nice library for using utility CSS classes

install it first and then create the config files using

npm i  tailwindcss autoprefixer postcss

For creating config files, run

npx tailwindcss init -p

If you have trouble installing it, we already covered this topic and you can find more details in [my link][2]

Finally we need to install firebase which a backend API that can be used for creating, validating login and password

npm i firebase

and then create the config files and link them to your next.js app.

This part will be necessary only if you would like to validate you login against a backend and we already covered the firebase configuration with Next.js in this topic

Build the login form

Once all the necessary libraries has been installed, we are going to build our login page

Create pages/login.js

import {getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import Link from 'next/link';
import {useRouter} from 'next/router';
import {useState} from 'react';
import Head from 'next/head';

export default function Login() {
	const [user, setUser] = useState({username: '', password: ''});
	const router = useRouter();

	const signIn = () => {
		const auth = getAuth();

		signInWithEmailAndPassword(auth, user.username, user.password)
			.then((userCredential) => {
				// Signed in
				router.push('/dashboard');
			})
			.catch((error) => {
				//  const errorCode = error.code;
				const errorMessage = error.message;
				//   console.log('login NOK ', errorCode,errorMessage)
				alert(errorMessage.split(':')[1]);
			});
	};

	return (
		<div>
			<div className="pb-2">
				<Link href="https://easyapply.vercel.app/">
					<a className=" p-2 text-3xl">Company </a>
				</Link>
			</div>
			<Head>
				<title>Company - Log in</title>
				<meta name="description" content="company" />
				<link
					href="/assets/blog/favicon.ico"
					rel="shortcut icon"
					type="image/x-icon"
				/>
			</Head>
			<div className="items-center justify-center flex h-screen">
				<div className="w-full max-w-xs">
					<form className="bg-white shadow-md rounded px-8 pt-6 pb-4 mb-2">
						<div className="mb-4">
							<label
								className="block text-gray-700 text-sm font-bold mb-2"
								htmlFor="username"
							>
								Username
							</label>
							<input
								className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
								id="username"
								type="text"
								placeholder="Username"
								onChange={(event) =>
									setUser({
										...user,
										username: event.target.value
									})
								}
							/>
						</div>
						<div className="mb-6">
							<label
								className="block text-gray-700 text-sm font-bold mb-2"
								htmlFor="password"
							>
								Password
							</label>
							<input
								className="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
								id="password"
								type="password"
								placeholder="******************"
								onChange={(event) =>
									setUser({
										...user,
										password: event.target.value
									})
								}
							/>
						</div>
						<div className="flex items-center justify-between">
							<button
								className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
								type="button"
								onClick={signIn}
							>
								Sign In
							</button>
						</div>
					</form>
					<div className="pb-2">
						<Link href="/signup">
							<a className="hover:underline px-2 text-xs">
								Don&apos;t have an account?
							</a>
						</Link>
					</div>
					<p className="text-center text-gray-500 text-xs">
						&copy;2022 Company Corp. All rights reserved.
					</p>
				</div>
			</div>
		</div>
	);
}

Our page is containing:

  • next/head part to set the page title and description, as well as using a favicon to be displayed on top of the browser to show our company logo, if you are interested on creating a favicon and linking it to your project, we have covered this topic, check details in this link
  • the form for user and password and how to hide it using the input property type password
  • A styled button for sign in, which triggers the signIn method when it is clicked
  • A user react state for handling the user and password and pass them to the signIn Method
  • A link on top right corner of the page for navigation, you can place a picture instead of a text if you wish to
  • A link to the sign up form, for now it is an empty page. Let me know down below in the contact us link whether you would like to cover the sign up form for you
  • The method signIn uses firebase signInWithEmailAndPassword method so that it checks login and password typed by the user against the values it has on database, if record matches , the user is routed to the dashboard page, else it returns an alert with the error message returned from firebase server
  • It is possible to remove the alert and implement the toast notification for the error which is a nicer way to show messages and attract user attention, check my article here for more details

Test the configuration

Now let’s run our server and run http://localhost:3000/login and you will be able to see the login page

login form in Next.js, tailwindcss

Notice the text highlighted in yellow for page name, and the favicon is displayed next to the page title

Now to test the sign in button, you need either to use firebase api in the sign up method or create a user manually in the firebase console.

To add a user manually in firebase console, you need to go the sign in method and add email/password provider to enable it as the picture down below is showing add provider for firebase

Once enabled go to users tab and add a new user as the picture show

add user in firebase

Now type the user and password you have created in firebase console to the login form, if the record matched you will be redirected to the dashboard, else the error message will pop up

Conclusion

We have seen how to create a login form easily with next.js and firebase as a backend for handling the sign in opertions

How to solve Your `getStaticPr...Easy guide for MUI autocomplet...


More interesting articles