Implementing Google Login in a Node.js Application
To implement Google Login, you need to set up a Google API project. Follow these steps:
- Go to the Google Developers Console (**https://console.developers.google.com/**).
- Create a new project or select an existing one.
- Enable the "Google+ API" for your project.
- Navigate to the "Credentials" section and click on "Create Credentials."
- Choose "OAuth client ID" as the credential type.
- Select "Web application" as the application type.
- Enter a name for your OAuth client ID.
- Add authorized JavaScript origins (e.g., http://localhost:3000) and redirect URIs (e.g., **http://localhost:3000/auth/google/callback**).
- Click "Create" to generate the client ID and client secret.
Step 2: Set Up the Node.js Project
Start by setting up a new Node.js project using a package manager like npm or yarn. Run the following command in your terminal:
csharpCopy code
npm init
This will create a package.json
file to manage your project's dependencies.
Step 3: Install Required Packages
To implement Google Login in Node.js, we need to install the necessary packages. Run the following command in your terminal:
Copy code
npm install express axios
This will install Express.js, a popular Node.js web framework, and the axios
package, which we will use to make HTTP requests.
Step 4: Implement the Authentication Routes
Create a new file, authRoutes.js
, to define the authentication routes for your application. In this file, implement the routes for initiating the Google Login flow, handling the callback URL, and logging out the user.
javascriptCopy code
const express = require('express');
const axios = require('axios');
const router = express.Router();
const CLIENT_ID = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const REDIRECT_URI = '<http://localhost:3000/auth/google/callback>';
// Initiates the Google Login flow
router.get('/auth/google', (req, res) => {
const url = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=profile email`;
res.redirect(url);
});
// Callback URL for handling the Google Login response
router.get('/auth/google/callback', async (req, res) => {
const { code } = req.query;
try {
// Exchange authorization code for access token
const { data } = await axios.post('<https://oauth2.googleapis.com/token>', {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
});
const { access_token, id_token } = data;
// Use access_token or id_token to fetch user profile
const { data: profile } = await axios.get('<https://www.googleapis.com/oauth2/v1/userinfo>', {
headers: { Authorization: `Bearer ${access_token}` },
});
// Code to handle user authentication and retrieval using the profile data
res.redirect('/');
} catch (error) {
console.error('Error:', error.response.data.error);
res.redirect('/login');
}
});
// Logout route
router.get('/logout', (req, res) => {
// Code to handle user logout
res.redirect('/login');
});
module.exports = router;
Make sure to replace 'YOUR_CLIENT_ID'
and 'YOUR_CLIENT_SECRET'
with your own credentials obtained from the Google API project.
Step 5: Set Up the Express.js Server
In your main server file (e.g., app.js
), import the required packages and configure the Express.js server. Include the authentication routes defined in authRoutes.js
.
javascriptCopy code
const express = require('express');
const authRoutes = require('./authRoutes');
const app = express();
app.use('/', authRoutes);
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
if you have any questions or suggestions just do let me know on my Instagram or at codeculturepro@gmail.com