⚠️ This tutorial is deprecated. Follow this tutorial instead (https://developers.google.com/identity/sign-in/web/backend-auth)
Authentication flow for MERN stack application using google OAuth 2.0.
This oauth flow is more secure and you don’t have to reload your react app and go through multiple redirections to authenticate client.
And the image blow is from google docs
1. Clone the repository & install dependencies
git clone https://github.com/Shahzayb/mern-google-login.git
cd client & npm install
2. Obtain OAuth 2.0 credentials from the Google API Console.
Visit the Google API Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application. Don’t store your client secret in your React app. You only need client id in your react app to get the authorization grant code. And you should store client secret in node app.
This is a url of client side react app
You’ll notice in my code that I set the
postmessage, its because we need the authorization grant code without any redirection
4. Client Side Setup
- execute these commands
.env.localfile & enter
REACT_APP_GOOGLE_CLIENT_ID=your client id provided by google
5. Server Side Environment Variables Setup
From the root directory of the project, type:
Note: These commands are for Mac/Linux users only. Windows users should type these commands in git bash
Now open the dev.env file and add
GOOGLE_CLIENT_ID=value from google apis,
GOOGLE_CLIENT_SECRET=value from google apis
6. Run ‘dev’ script
npm run dev
if you want more information, then please read the one-time-code flow implementation
Please help me with the documentation and improve the code. I’ll appreciate that. For changes, please open an issue first to discuss what you would like to change.