Olanrewaju Alaba
// terminal
node --version
// terminal
cd desktop
mkdir my-nodejs-app //create a project directory
cd my-nodejs-app // navigate to the app directory
npm init -y // create a default package.json file
npm install express dotenv passport passport-google-oauth20 express-session // install necessary dependencies
code . // to open the directory on my code editor (VS Code). You can do it manually.
--watch
flag. //package.json
{
"name": "my-nodejs-app",
"version": "1.0.0",
"description": "",
"type": "module", // add this to use the ES6
"main": "server.js", // update this to
"scripts": {
"dev": "node --watch server.js" // script to run a development server
},
"keywords": [],
"author": "",
"license": "ISC",
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-session": "^1.18.0",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0"
}
}
server.js
file in the base of the directory to set up our project server. // server.js
// import necessary depenencies
import "dotenv/config";
import express from "express";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import session from "express-session";
// intialize app and define the server port
const app = express();
const port = process.env.PORT || 8000;
// a middleware to access json data
app.use(express.json());
// a view to check if the server is running properly
// check `http://127.0.0.1:${port}/` -> http://127.0.0.1:800
app.get("/", (req, res) => {
res.send(`My Node.JS APP`);
});
// a function to start the server and listen to the port defined
const start = async () => {
try {
app.listen(port, () => console.log(`server is running on port ${port}`));
} catch (error) {
console.log(error);
}
};
// call the function
start();
.env
file dotenv
dependency is installed and imported into your server.js
file. Use the format below to set the .env file. //.env
// make sure these values are correct
GOOGLE_CLIENT_ID= // your google client id
GOOGLE_CLIENT_SECRET= // your google client client
SESSION_SECRET= // any randome secure characters
PORT= 8000 // define port from the env file
passport.js
file utils
folder in the project directory base and create passport.js
file. This is where the connection of our Node.js app to the Google Oauth App created on the Google console takes place. Check the code snippet.server.js
npm run dev