{"id":19606770,"url":"https://github.com/learnwithfair/mern-google-authentication","last_synced_at":"2026-03-19T10:45:47.514Z","repository":{"id":238082362,"uuid":"795831761","full_name":"learnwithfair/mern-google-authentication","owner":"learnwithfair","description":"mern-google-authentication with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]","archived":false,"fork":false,"pushed_at":"2024-05-04T08:31:48.000Z","size":14,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-26T16:50:01.725Z","etag":null,"topics":["google-auth","google-authentication","learn-with-fair","learnwithfair","mern-google-authentication","rahatul-rabbi","rahatulrabbi","sign-in-with-google","web-development"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/learnwithfair.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-05-04T07:25:15.000Z","updated_at":"2024-05-04T08:31:51.000Z","dependencies_parsed_at":"2024-05-04T08:37:40.449Z","dependency_job_id":null,"html_url":"https://github.com/learnwithfair/mern-google-authentication","commit_stats":null,"previous_names":["learnwithfair/mern-google-authentication"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/learnwithfair/mern-google-authentication","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-google-authentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-google-authentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-google-authentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-google-authentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learnwithfair","download_url":"https://codeload.github.com/learnwithfair/mern-google-authentication/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-google-authentication/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29984724,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-01T21:06:37.093Z","status":"ssl_error","status_checked_at":"2026-03-01T21:05:45.052Z","response_time":124,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["google-auth","google-authentication","learn-with-fair","learnwithfair","mern-google-authentication","rahatul-rabbi","rahatulrabbi","sign-in-with-google","web-development"],"created_at":"2024-11-11T10:07:09.650Z","updated_at":"2026-03-01T21:33:34.605Z","avatar_url":"https://github.com/learnwithfair.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# MERN-GOOGLE-AUTHENTICATION\n\n[![Youtube][youtube-shield]][youtube-url]\n[![Facebook][facebook-shield]][facebook-url]\n[![Instagram][instagram-shield]][instagram-url]\n[![LinkedIn][linkedin-shield]][linkedin-url]\n\nThanks for visiting my GitHub account!\n\n\u003cimg src =\"https://miro.medium.com/v2/resize:fit:548/1*KEtWAhxgLOKU8Sd1np4Phg.png\" height = \"200px\" width = \"200px\"/\u003e**Sign in with Google** makes it easy for you to sign in and sign up to websites and apps across the internet with the trusted security of your Google Account. It eliminates your dependency on passwords, which reduces the frustrations and security risks associated with them. [see-more](https://blog.logrocket.com/guide-adding-google-login-react-app/)\n\n### [Code-Example](https://github.com/learnwithfair/mern-user-admin-authentication)\n\n## Source Code (Download)\n\n- [Source-code](https://mega.nz/file/JTEAFQSb#ofhBa2_ySO8n253pS3di2rG-NDomk_4bpO2yIqS4VjY)\n- [Documentation](https://github.com/learnwithfair/node-express-documentation)\n\n## Required Software (Download)\n\n- VS Code, Download -\u003ehttps://code.visualstudio.com/download\n- Node, Download-\u003e https://nodejs.org/en/download\n- MongoDB Shell(msi) , Download-\u003e https://www.mongodb.com/try/download/shell\n- MongoDB Compass (msi), Download-\u003e https://www.mongodb.com/try/download/community\n- Postman, Download-\u003e https://www.postman.com/downloads/\n\n**Or Online Database (MongoDB Atlas)**\n\n- Register -\u003e https://www.mongodb.com/cloud/atlas/register\n\n## ========== Environment Setup ==========\n\n1. Install Node.js\n2. To verify installation into command form by node -v\n3. For initialization npm write the query in the command window as npm init -y\n4. Setup the opening file into the package.json and change the file with main:'server.js'\n5. To create a server using the express package then write a query into the command window as npm install express.\n   Write code in the server file for initialization\n   const express = require(\"express\");\n   const app = express();\n   app.listen(3000, () =\u003e {\n   console.log(\"Server is running at http://localhost:3000\");\n   });\n\n6. Install the nodemon package for automatically running the server as- npm i --save-dev nodemon (For Developing purpose)\n7. setup the package.json file in the scripts key, write\n   \"scripts\": {\n   \"start\": \"node ./resources/backend/server.js\",\n   \"dev\": \"nodemon ./resources/backend/server.js\",\n   \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\"\n   },\n8. use the Morgan package for automatic restart. Hence install the morgan package as npm install --save-dev morgan (Development purpose)\n   Write code in the server file for initialization\n   const morgan = require(\"morgan\");\n   app.use(morgan(\"dev\")); --\u003e Middlewire.\n9. Install Postman software for API testing by the URL endpoint.\n10. Install Mongobd + MongobdCompass and Mongoshell (For Database)\n\n## ========== Connect MongoDB Database ==========\n\n1. Install Mondodb + Mongodb Compass and Mongodb Shell download from the google.\n2. Set up Environment Variable in drive:c/program file\n3. Create a directory in the base path of the c drive named data. Inside the data directory create another folder db.\n4. Write the command in the CMD window as Mongod. And write the other command in the other CMD window as mongosh.\n5. Then Check the version as mongod --version and mongosh --version.\n6. Install mongoose package as npm i mongoose\n7. Create an atlas account. In the atlas account create a cluster that have a user(as atlas admin) and network access with any access IP address.\n8. Connect the database using URL from the atlas cluster or local Mongodb compass using the mongoose package as mongoose. connect('mongodb://localhost:27017/database-name);\n\n## How to use this template\n\n- Step-1: In the Frontend site\n\n```js\nimport React, { useEffect } from \"react\";\nimport GoogleLogin from \"react-google-login\";\nimport { gapi } from \"gapi-script\";\nimport { loginWithGoogle } from \"../services/AuthService\";\n\nconst Google = () =\u003e {\n  const responseGoogle = async (response) =\u003e {\n    try {\n      // 1. get the tokenId from response\n      console.log(response.tokenId);\n\n      // 2. send the tokenId to the server\n      const result = await loginWithGoogle({ idToken: response.tokenId });\n      console.log(\"Google signin success: \", result);\n    } catch (error) {\n      console.log(\"Google signin error: \", error.response.data.message);\n    }\n  };\n\n  useEffect(() =\u003e {\n    function start() {\n      gapi.client.init({\n        clientId: process.env.REACT_APP_CLIENT_ID,\n        scope: \"email\",\n      });\n    }\n\n    gapi.load(\"client:auth2\", start);\n  }, []);\n\n  return (\n    \u003cdiv className=\"pb-3\"\u003e\n      \u003cGoogleLogin\n        clientId={`${process.env.REACT_APP_CLIENT_ID}`}\n        render={(renderProps) =\u003e (\n          \u003cbutton\n            onClick={renderProps.onClick}\n            disabled={renderProps.disabled}\n            className=\"btn btn-danger btn-lg btn-block\"\n          \u003e\n            \u003ci className=\"fab fa-google p-2\"\u003e\u003c/i\u003eLogin With Google\n          \u003c/button\u003e\n        )}\n        onSuccess={responseGoogle}\n        onFailure={responseGoogle}\n        cookiePolicy={\"single_host_origin\"}\n      /\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default Google;\n```\n\n- Step-2: In the `services/AuthService` path\n\n```js\nexport const loginWithGoogle = async (data) =\u003e {\n  const response = await axios.post(\n    `http://localhost:3030/api/google-login`,\n    data\n  );\n  return response.data;\n};\n```\n\n- Step-3: In the Server site\n\n  - install `npm install google-auth-library`\n\n```js\n// google\nauthRoutes.post(\"/google-login\", handleGoogleLogin);\n\nconst { OAuth2Client } = require(\"google-auth-library\");\nconst jwt = require(\"jsonwebtoken\");\n\nconst handleGoogleLogin = async (req, res) =\u003e {\n  try {\n    // creating client which help us to verify the idToken that we receive from front end\n    const client = new OAuth2Client(dev.app.googleClientId);\n\n    // get the idToken form react app request body\n    const { idToken } = req.body;\n    console.log(\"idToken \", idToken);\n\n    // lets verify the idToken\n    client\n      .verifyIdToken({ idToken, audience: dev.app.googleClientId })\n      .then(async (response) =\u003e {\n        console.log(\"GOOGLE LOGIN RESPONSE\", response);\n        const { email_verified, name, email } = response.payload;\n\n        const exsitingUser = await User.findOne({ email });\n        if (email_verified) {\n          // if the user already exist in our website\n          if (exsitingUser) {\n            console.log(\"user exist\");\n            // create a token for user\n            const token = jwt.sign(\n              { _id: exsitingUser._id },\n              String(dev.app.jwtSecretKey),\n              {\n                expiresIn: \"7d\",\n              }\n            );\n\n            // step 7: create user info\n            const userInfo = {\n              _id: exsitingUser._id,\n              name: exsitingUser.name,\n              email: exsitingUser.email,\n              phone: exsitingUser.phone,\n              isAdmin: exsitingUser.isAdmin,\n            };\n\n            return res.json({ token, userInfo });\n          } else {\n            // if user does not exist create a new user\n            let password = email + dev.app.jwtSecretKey;\n            const newUser = new User({\n              name,\n              email,\n              password,\n            });\n\n            // console.log(newUser);\n\n            const userData = await newUser.save();\n            if (!userData) {\n              return res.status(400).send({\n                message: \"user was not created with google\",\n              });\n            }\n\n            // if user is created\n            const token = jwt.sign(\n              { _id: userData._id },\n              String(dev.app.jwtSecretKey),\n              {\n                expiresIn: \"7d\",\n              }\n            );\n\n            // step 7: create user info\n            const userInfo = {\n              _id: userData._id,\n              name: userData.name,\n              email: userData.email,\n              phone: userData.phone,\n              isAdmin: userData.isAdmin,\n            };\n\n            return res.json({ token, userInfo });\n          }\n        } else {\n          return res.status(400).send({\n            message: \"Google login failed try again\",\n          });\n        }\n      });\n  } catch (error) {\n    res.send({\n      message: error.message,\n    });\n  }\n};\n```\n\n- Step-4: Setup .env file in the server folder\n\n```env\nSERVER_PORT=8080\nMONGODB_URL=\nJWT_ACCOUNT_ACTIVATION_KEY=\nJWT_RESET_PASSWORD_KEY=\nJWT_ACCESS_TOKEN_KEY=\nJWT_REFRESH_TOKEN_KEY=\nSMTP_USERNAME=YOUR_GMAIL_HERE\nSMTP_PASSWORD=\nCLIENT_URL=\nSESSION_SECRET=\nGOOGLE_CLIENT_ID=\nGOOGLE_CLIENT_SECRET=\n\n```\n\n\n- Step-5: Setup for secret key\n\n```js\nrequire(\"dotenv\").config();\n\nconst dev = {\n  db: {\n    mongoURL:\n      process.env.MONGODB_URL || \"mongodb://127.0.0.1:27017/database-name\",\n  },\n  app: {\n    port: process.env.SERVER_PORT || 8000,\n    jwtAccountActivationKey: process.env.JWT_ACCOUNT_ACTIVATION_KEY,\n    jwtResetPasswordKey: process.env.JWT_RESET_PASSWORD_KEY,\n    jwtAcessTokenKey: process.env.JWT_ACCESS_TOKEN_KEY,\n    jwtRefreshTokenKey: process.env.JWT_REFRESH_TOKEN_KEY,\n    smtpUsername: process.env.SMTP_USERNAME,\n    smtpPassword: process.env.SMTP_PASSWORD,\n    clientUrl: process.env.CLIENT_URL,\n    googleClientId: process.env.GOOGLE_CLIENT_ID,\n    googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,\n  },\n};\n\nmodule.exports = dev;\n```\n\n\n## Follow Me\n\n[\u003cimg src='https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/github.svg' alt='github' height='40'\u003e](https://github.com/learnwithfair) [\u003cimg src='https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/facebook.svg' alt='facebook' height='40'\u003e](https://www.facebook.com/learnwithfair/) [\u003cimg src='https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/instagram.svg' alt='instagram' height='40'\u003e](https://www.instagram.com/learnwithfair/) [\u003cimg src='https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/twitter.svg' alt='twitter' height='40'\u003e](https://www.twiter.com/learnwithfair/) [\u003cimg src='https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/youtube.svg' alt='YouTube' height='40'\u003e](https://www.youtube.com/@learnwithfair)\n\n\u003c!-- MARKDOWN LINKS \u0026 IMAGES --\u003e\n\n[youtube-shield]: https://img.shields.io/badge/-Youtube-black.svg?style=flat-square\u0026logo=youtube\u0026color=555\u0026logoColor=white\n[youtube-url]: https://youtube.com/@learnwithfair\n[facebook-shield]: https://img.shields.io/badge/-Facebook-black.svg?style=flat-square\u0026logo=facebook\u0026color=555\u0026logoColor=white\n[facebook-url]: https://facebook.com/learnwithfair\n[instagram-shield]: https://img.shields.io/badge/-Instagram-black.svg?style=flat-square\u0026logo=instagram\u0026color=555\u0026logoColor=white\n[instagram-url]: https://instagram.com/learnwithfair\n[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square\u0026logo=linkedin\u0026colorB=555\n[linkedin-url]: https://linkedin.com/company/learnwithfair\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fmern-google-authentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearnwithfair%2Fmern-google-authentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fmern-google-authentication/lists"}