{"id":19606731,"url":"https://github.com/learnwithfair/mern-facebook-authentication","last_synced_at":"2026-03-19T10:45:47.189Z","repository":{"id":238084885,"uuid":"795837398","full_name":"learnwithfair/mern-facebook-authentication","owner":"learnwithfair","description":"mern-facebook-authentication with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]","archived":false,"fork":false,"pushed_at":"2024-05-04T08:31:22.000Z","size":13,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-09T09:24:22.299Z","etag":null,"topics":["api","facebook-auth","facebook-authentication","learn-with-fair","learnwithfair","login-with-facebook","mern","rahatul-rabbi","rahatulrabbi","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:47:49.000Z","updated_at":"2024-05-04T08:31:26.000Z","dependencies_parsed_at":"2024-05-04T08:43:17.355Z","dependency_job_id":null,"html_url":"https://github.com/learnwithfair/mern-facebook-authentication","commit_stats":null,"previous_names":["learnwithfair/mern-facebook-authentication"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-facebook-authentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-facebook-authentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-facebook-authentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmern-facebook-authentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learnwithfair","download_url":"https://codeload.github.com/learnwithfair/mern-facebook-authentication/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240894498,"owners_count":19874823,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["api","facebook-auth","facebook-authentication","learn-with-fair","learnwithfair","login-with-facebook","mern","rahatul-rabbi","rahatulrabbi","web-development"],"created_at":"2024-11-11T10:07:03.021Z","updated_at":"2026-02-24T20:35:09.257Z","avatar_url":"https://github.com/learnwithfair.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# MERN-FACEBOOK-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://logowik.com/content/uploads/images/sign-in-with-facebook-button1655.jpg\" height = \"200px\" width = \"200px\"/\u003e**Sign in with Facebook** makes it easy for you to sign in and sign up to websites and apps across the internet with the trusted security of your Facebook Account. It eliminates your dependency on passwords, which reduces the frustrations and security risks associated with them. [see-more](https://dev.to/quod_ai/how-to-integrate-facebook-login-api-into-your-react-app-33de)\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/oD1iWSLT#OEKyk_qDwdnbIqTFGYc8xAbY0QEokyH8paAA2PBKYdU)\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: get facebook client id\n\n  - visit url-\u003e https://developers.facebook.com/\n  - register as developer\n  - create new app as consumer\n  - `npm install react-facebook-login`\n  - change in package.json `\"start\": \"HTTPS=true react-scripts start\",`\n\n- Step-2: In the Frontend site\n\n```js\n// Facebook.js\nimport React from \"react\";\nimport FacebookLogin from \"react-facebook-login/dist/facebook-login-render-props\";\nimport { loginWithFacebook } from \"../services/AuthService\";\n\nconst Facebook = () =\u003e {\n  const responseFacebook = async (response) =\u003e {\n    try {\n      // 1. send the userID and accessToken to the server\n      const result = await loginWithFacebook({\n        userID: response.userID,\n        accessToken: response.accessToken,\n      });\n      console.log(\"Facebook signin success: \", result);\n    } catch (error) {\n      console.log(error);\n      console.log(\"Facebook signin error: \", error.response.data.message);\n    }\n  };\n\n  return (\n    \u003cdiv className=\"pb-3\"\u003e\n      \u003cFacebookLogin\n        appId=\"3326779317563993\"\n        autoLoad={false}\n        callback={responseFacebook}\n        render={(renderProps) =\u003e (\n          \u003cbutton\n            onClick={renderProps.onClick}\n            className=\"btn btn-danger btn-lg btn-block\"\n          \u003e\n            \u003ci className=\"fab fa-facebook p-2\"\u003e\u003c/i\u003eLogin With Facebook\n          \u003c/button\u003e\n        )}\n      /\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default Facebook;\n```\n\n- Step-3: In the `services/AuthService` path\n\n```js\nexport const loginWithFacebook = async (data) =\u003e {\n  const response = await axios.post(\n    `http://localhost:3030/api/facebook-login`,\n    data\n  );\n  return response.data;\n};\n```\n\n- Step-4: In the Server site\n\n  - install `npm install node-fetch@2`\n\n```js\n// facebook\nauthRoutes.post(\"/facebook-login\", handleFacebookLogin);\n```\n\n- **Controller part**\n\n```js\nconst fetch = require(\"node-fetch\");\nconst handleFacebookLogin = async (req, res) =\u003e {\n  try {\n    const { userID, accessToken } = req.body;\n\n    // create the url for requesting userInfo\n    const url = `http://graph.facebook.com/v2.11/${userID}/?fields=id,name,email\u0026access_token=${accessToken}`;\n\n    // make the request with fetch api\n    const response = await fetch(url);\n    const data = await response.json();\n    const { name, email, id } = data;\n\n    // check user with this email already exist or not\n    const exsitingUser = await User.findOne({ email });\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      };\n\n      return res.json({ token, userInfo });\n    } else {\n      // if user does not exist create a new user\n      // let create a dummy password\n      let password = email + dev.app.jwtSecretKey;\n      const newUser = new User({\n        name,\n        email,\n        password,\n      });\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\n    res.send(\"facebook login successful\");\n  } catch (error) {\n    res.status(500).send({\n      message: error.message,\n    });\n  }\n};\n```\n\n- Step-5: 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- Step-6: Setup for secrect 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## 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-facebook-authentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearnwithfair%2Fmern-facebook-authentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fmern-facebook-authentication/lists"}