DEV Community

Cover image for Guest Login in JavaScript 🤯
Rajesh Joshi
Rajesh Joshi

Posted on • Edited on

Guest Login in JavaScript 🤯

Whether a project is small, medium, or huge, it's most common necessity is authentication. In few cases, it is just required to not to ask user for credentials, but just to log user in for proper authentication.

The best way to solve this problem is to use Firebase's Anonymous Authentication.

NOTE: Here's the YouTube video of me, demonstrate the same

NOTE:: I'll recommend you, to use the yarn, but it is completely up to you.


Step 1. Create React App

$ npx create-react-app fbase
Enter fullscreen mode Exit fullscreen mode

Step 2. Add firebase

$ yarn add firebase
Enter fullscreen mode Exit fullscreen mode

It'll be reflected in package.json file.

{
  "name": "fbase",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^9.6.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3. Create firebaseConfig.json file, and paste the firebase configurations

{
  "apiKey": "AIzygy_MxOabWfYylrZcr_A0qikixlwIynwvgE",
  "authDomain": "learn-00000.firebaseapp.com",
  "projectId": "learn-00000",
  "storageBucket": "learn-00000.appspot.com",
  "messagingSenderId": "708886134942",
  "appId": "1:708886134942:web:e9162122e8cd6741ca7b8f",
  "measurementId": "G-M5TXS27GDQ"
}
Enter fullscreen mode Exit fullscreen mode

Step 4. Write app.js

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import firebaseConfig from "./firebaseConfig.json";

initializeApp(firebaseConfig);

const auth = getAuth();

export default function App() {

  return ();
}
Enter fullscreen mode Exit fullscreen mode

Now, create Flexbox

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import firebaseConfig from "./firebaseConfig.json";

initializeApp(firebaseConfig);

const auth = getAuth();

export default function App() {

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <h1>Anonymous Login</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Add HTML form

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import firebaseConfig from "./firebaseConfig.json";

initializeApp(firebaseConfig);

const auth = getAuth();

export default function App() {

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <h1>Anonymous Login</h1>
      <form onSubmit={handleSubmit}>
        <button type="submit">Login</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

define onSubmit method.


import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import firebaseConfig from "./firebaseConfig.json";

initializeApp(firebaseConfig);

const auth = getAuth();

export default function App() {
  const handleSubmit = (e) => {
    e.preventDefault();

    // ...
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <h1>Anonymous Login</h1>

      <form onSubmit={handleSubmit}>
        <button type="submit">Login</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Import signInAnonymously


import { getAuth, signInAnonymously } from "firebase/auth";

Enter fullscreen mode Exit fullscreen mode

Now, extend handleSubmit


import { initializeApp } from "firebase/app";
import { getAuth, signInAnonymously } from "firebase/auth";
import firebaseConfig from "./firebaseConfig.json";

initializeApp(firebaseConfig);

const auth = getAuth();

export default function App() {
  const handleSubmit = (e) => {
    e.preventDefault();

    signInAnonymously(auth)
      .then()
      .catch();
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <h1>Anonymous Login</h1>

      <form onSubmit={handleSubmit}>
        <button type="submit">Login</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Write, responses


import { initializeApp } from "firebase/app";
import { getAuth, signInAnonymously } from "firebase/auth";
import firebaseConfig from "./firebaseConfig.json";

initializeApp(firebaseConfig);

const auth = getAuth();

export default function App() {
  const handleSubmit = (e) => {
    e.preventDefault();

    signInAnonymously(auth)
      .then((res) => {
        console.log("[Sign In] DONE", res.user.uid);
      })
      .catch((error) => {
        console.log(error.message);
      });
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <h1>Anonymous Login</h1>

      <form onSubmit={handleSubmit}>
        <button type="submit">Login</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Step 5. Run the server

$ yarn start
Enter fullscreen mode Exit fullscreen mode

click Login button and Open developer console.

Login

In Applications > IndexedDB you'll see user credentials saved.

IndexedDB

Step 6. Have a look in Firebase Console

Firebase Console


Hurray! You just learned how to set up API end-points for Login Without Email and Password in JavaScript.


I hope, you guys liked this quick tutorial. If so, then please don't forget to drop a Like ❤️

And also, help me reach 1k Subscribers 🤩, on my YouTube channel.

Happy Coding! 😃💻

Top comments (15)

Collapse
 
mcwolfmm profile image
mcwolfmm

show image code? are you serious?

to talk about login, you need to associate the user ID with a session. add another collection of session data and the article may make some sense.

and for god's sake, don't give the code a picture

Collapse
 
rajeshj3 profile image
Rajesh Joshi

As per the request, I've provided the code this time.

Collapse
 
pbatey profile image
Phil Batey

I don’t understand the use case for anonymous login.

Will the user credentials persist across sessions?

What happens if they close their browser?

Collapse
 
premierdan profile image
premierdan

Honestly, this needs further clarification.

Collapse
 
premierdan profile image
premierdan

🙏

Collapse
 
rajeshj3 profile image
Rajesh Joshi

Your thought is obvious, in normal situations Anonymous authentication is rare and there is no such requirements as well.

But, if you look into some specific kind of softwares like, Mobile Games (PUBG for example). It is really handy to have Anonymous authentication (also known as Guest Login) both for game testers or end users in general.

In those kinds of applications, the functionality to adding Google, Facebook, Twitter, etc. accounts in the future is possible, to persist the user data, which is also possible in Firebase as well.

I hope this answers your question buddy.

Thanks 😊

Collapse
 
rajeshj3 profile image
Rajesh Joshi

Will the user credentials persist across sessions?

Yes, the session will persist untill you remove the user data from indexedDB or the session expires.

What happens if they close their browser?

The session will persist even after you restart your system itself.

Collapse
 
cbretus profile image
cb-retus

I see the authentication token is in the code, of course, but is this part exposed in javascript aka in the browser?

if that's the case, I wouldn't recommend this approach.

I worked 6½ year in an online gambling company and we knew that client-side information such as authentication tokens is a no-go, even for guest-logins.

You could make a "Session" service and let it produce a session token and then send that to the guest, then each authentication token would be unique + you need a server side way of expiring these tokens too.

I hope and assume you use Firebase for that purpose?

Collapse
 
ats1999 profile image
Rahul kumar

You can embed the cide

Collapse
 
rajeshj3 profile image
Rajesh Joshi

Hey, as per your request, I've provided the code this time.

Collapse
 
daasrattale profile image
Elattar Saad

Hi fella,
The article is good, such I have some point you may want to know:
Please, don't put screenshots of code it's really hard for people to try your example (or you may want to associate this article article with GitHub repo).
Don't mind to the toxicity of some comments, but we need a clearer use case for the anonymous auth (why should we use it).
Please feel free to contact me is you need any kind of guidance.
My regards.

Collapse
 
rajeshj3 profile image
Rajesh Joshi

As per the request, I've provided the code.

As you asked, "why should we use it"

There are lot of case scenerios where we needs Guest Login. This article helps you out in implementing that case.

Collapse
 
dmitryame profile image
Info Comment hidden by post author - thread only accessible via permalink
Dmitry Amelchenko

What is the purpose of creating authentication in the first place?
Is it necessary to allow the centralized server to know who you are?
What if, instead, the users would notify only their friends, who they actively interact with, about their identity, leaving the information stored in the centralized server completely de-anonymized?

Read more about this approach at following link:
dev.to/dmitryame/p4p-peer-4-peer-i...

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more