Notes on 3rd round of Node.js, Express.js, Mongoose and MongoDB tutorials with quick refresher of (simple) Blog full stack app
Last updated on 30 Sep. 2024
Note: I had done first and second round of Full Stack (MERN) web development based on my roadmap with second round getting over sometime in March 2024. The first and second round notes of sections related to Node, Express, Mongoose and MongoDB can be viewed here: https://raviswdev.blogspot.com/2024/03/learning-web-app-development-through.html#nodejsexpressjs . I don't think there is a clear differentiation between notes of 1st and 2nd rounds.
24 Sep. 2024: Started refreshing my Node.js and Node Express learning. I think the last time I did non-trivial Node.js, Express (or Mongoose/MongoDB) was in March 2024. So there has been a break of around 6 months.
In express tutorial, methods-public\styles.css uses:
h5 + h5 {
margin-left: 1rem;
}
----
The '+' is an adjacent sibling selector. Ref: '+ (plus) Sign:' section in Understand '+', '>' and '~' symbols in CSS Selector, https://techbrij.com/css-selector-adjacent-child-sibling
27 Sep. 2024: Finished refresher of 1st video: Node.js and Express.js - Full Course, https://www.youtube.com/watch?v=Oe421EPjeBE .
Now I have to move on to initial part of 2nd video: Node.js Projects, https://www.youtube.com/watch?v=rltfdjcXjmk ... This initial part covers MongoDB and Mongoose in the first project (TASK MANAGER). This coverage is from beginning of video till around 3 hrs 7 mins after which the next project (STORE API) starts. In my first round I had stopped after the first project (TASK MANAGER) part.
======================
28 Sep. 2024.
Watched 2nd video till Tasks project finish (around 3 hrs. 7 mins) which is where I had stopped first round.
I was able to run the final Tasks project easily with MongoDB connection working properly - getting data from db and updating data on db.
Need to go through all of final back-end source code to ensure I have not missed out some code in this 2nd round. The tutorial breezes over the plain vanilla JS front-end. I think I will try to have a quick look at it which I have not done so far in this 2nd round.
--------------
29 Sep. 2024:
Quickly went through all of final back-end source code ...
In final\controllers\tasks.js we have:
const task = await Task.findOne({ _id: taskID })
---
Mongoose docs examples in https://mongoosejs.com/docs/api/model.html#Model.findOne() chain .exec() to findOne :
await Adventure.findOne({ country: 'Croatia' }).exec();
----
Don't know the details of why docs use .exec(). But I don't think it is worth investing experimentation time for this. It would have been great if official docs explained it either here or elsewhere with a link to that other page. But I could not find such info. in this section of the mongoose docs.
----------
Had a very quick look at plain vanilla JS front-end - omitted going through css files. I don't think it is appropriate to invest time in going through this code in detail as I don't think I will be using plain vanilla JS front-end. But I was able to recall my first round work of going through these files and was able to get a grasp of how the front-end js and html code operate, including axios calls to the back-end API which is the important part.
=========================
JSON Web Token (JWT)
Went through article mentioned in 1st/2nd rounds: Node.js User Authentication Guide, https://www.loginradius.com/blog/engineering/guest-post/nodejs-authentication-guide/ , Jan. 2022. GitHub: https://github.com/LoginRadius/engineering-blog-samples/tree/master/NodeJs/NodejsAuthenticationGuide . The first part of the article which is the main article, comes across as a good example of doing authentication with own code (as against using some packages), which includes roles of basic user and admin, along with JWT with MongoDB as the database and Mongoose as library to use MongoDB. I have not tried out the code and understood every detail of it but I think that if I do need JWT authentication to be done with own code, I could then try out this code, and if it works out fine, use it.
Went through next article mentioned in 1st round: Build a Secure Authentication System with NodeJS and MongoDB, https://medium.com/@anandam00/build-a-secure-authentication-system-with-nodejs-and-mongodb-58accdeb5144 , Apr. 2023 . It is somewhat similar to above though not as detailed, and it does not have front-end. Further, GitHub repo link does not seem to be available. However, the code given in the article seems to cover all the basic ground needed for JWT authentication including registering user and hashing the password. But it does not cover role based auth.
===========================
Now am moving on to: https://raviswdev.blogspot.com/2024/03/learning-web-app-development-through.html#mernminiproject which covers the Full Stack mini project that I had done in the 1st & 2nd rounds (Simple blog app with React Front-End and Node Express/Mongoose/MongoDB as Back-End).
Am going through my blog posts linked in the above section (e.g. 'Notes on creating Node Express & MongoDB (simple) Blog API and refactoring React tutorial Blog App to use it') , and finding them to be very useful for refreshing my knowledge.
Looked up GitHub to see which project directories on PC match latest commits on GH repositories for Blog Full Stack project.
react_blog_fs_netlify, https://github.com/ravisiyer/react_blog_fs_netlify seems to be the frontend repo. Its latest commit is: Added README to attribute Dave Gray's React tutorial, 6f11842f2a9226ffbc6a50fba74cbd6415a369cf dated Mar 18, 2024. This matches with latest commit on PC project with path: ...\RaviAddn\CodeAlongWithVariation\cawv-cur .
...\RaviAddn\CodeAlongWithVariation\netlify-deploys-readme.txt mentions "New commit: "Added README to attribute Dave Gray's React tutorial" and push to Github react_blog_fs_netlify project made at 7:37 PM on 18. Mar. 2024. cawv-1607dp-blog-FS-README folder has the associated source code." Using WinMerge, I confirmed that that cawv-1607dp-blog-FS-README folder's source code matches cawv-cur.
It is deployed at: https://ravisiyerblogfs.netlify.app/ but gives a network error (as the backend - https://easy-pear-pike-suit.cyclic.app/api/posts - is not deployed due to the host cyclic.sh closing down).
-----------
BlogTutAPI, https://github.com/ravisiyer/BlogTutAPI seems to be the backend repo. Its latest commit is: Update README.md to provide attribution to John Smilga Node Express tutorial, 4180b2d626eea14ee06c4265853b4b23b5f9fa02 , dated Mar 18, 2024. This matches with latest commit on PC project with path: ...\Node\RaviAddn\BlogAPI\cur-ver .
...\Node\RaviAddn\BlogAPI\info-log.txt states, "10-ReadmeUpd-gitpull folder the source code for abovementioned github pulled version. Github project: https://github.com/ravisiyer/BlogTutAPI , Commit message is: "Update README.md to provide attribution to John Smilga Node Express tutorial" and commit time is: Mar. 18, 2024, 5:41 PM". Using WinMerge, I confirmed that that 10-ReadmeUpd-gitpull folder's source code matches cur-ver.
It was deployed on cyclic.sh but that company seems to have shut down! I need to explore other free deployment options.
-----------
[A related repo but which uses local storage and not a full stack app, if I recall correctly, is: react_cawv_blog_ls, https://github.com/ravisiyer/react_cawv_blog_ls. Its latest commit is: Updated README and minor UI change, 8bea7d88d1061729d090db49a48c01d9ba5848c1 , dated Mar 18, 2024.
...\RaviAddn\CodeAlongWithVariation\react_cawv_blog_ls PC project has a matching last commit.
...\RaviAddn\CodeAlongWithVariation\cawv-1701-blog-LS-nelify-deploy folder source code matches above react_cawv_blog_ls project as per WinMerge.
It is deployed at: https://ravisiyerblog.netlify.app/. I checked it out both on PC and mobile, and it seems to be working properly. Great to see that after 6 months gap, the app deployment is still working without any issues, even for a free plan user.]
-----------
Ran the PC project BlogTutAPI (...\Node\RaviAddn\BlogAPI\cur-ver on port 4000) and PC project react_blog_fs_netlify (...\RaviAddn\CodeAlongWithVariation\cawv-cur on port 3000). Both programs worked right away. But one issue was that I had forgotten the passwords. So created a test user using createuser.js in usercmds in the project, after deleting the earlier test users (directly on MongoDB). That created the specified test user with specified password (on MongoDB) and I was able to use that to log in to backend running on PC from React frontend. The FS app (frontend and backend) seems to be working correctly on PC.
------
Have started going through source code of PC project BlogTutAPI (...\Node\RaviAddn\BlogAPI\cur-ver). Some notes on it ...
In app.js :
try {
await connectDB(process.env.MONGO_URI);
console.log("Just after await connectDB(). Presumably connected to DB ...");
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
} catch (err) {
console.log(`Failed to connect to DB. ... ${err}`);
}
----
I tried to search my posts for why I am using the 'presumably connected' phrase but did not get suitable results. Perhaps I did not clearly understand the mechanism of connectDB function returning a promise and app.js code await(ing) on the promise. Had a quick look at Mongoose docs: https://mongoosejs.com/docs/connections.html . Looks like if there is no exception thrown and promise is resolved (code after await starts executing), we can say that we are connected to database. I think the word presumably can be dropped.
-----
In controllers\posts.js:
const getPost = asyncWrapper(async (req, res, next) => {
const { postID } = req.params;
console.log(postID);
const post = await Post.findOne({ _id: postID }).exec();
...
--------
The code uses findOne(...).exec() whereas the Smilga tutorial code for Task Manager uses only findOne(...) without .exec().
...
Got the docs page explaining it! Should You Use exec() With await?, https://mongoosejs.com/docs/promises.html#should-you-use-code%3Eexec()%3C/code%3E-with-%3Ccode%3Eawait%3C/code%3E? :
There are two alternatives for using await with queries:
await Band.findOne();
await Band.findOne().exec();
As far as functionality is concerned, these two are equivalent. However, we recommend using .exec() because that gives you better stack traces.
----
Basic Authentication is used in the BlogTutAPI. This is a major difference from Smilga tutorial Task Manager. My blog post: Notes on adding authentication to blog tutorial app on frontend and backend, https://raviswdev.blogspot.com/2024/03/notes-on-adding-authentication-to-blog.html covers this additional code.
An additional point is that the package I used: https://www.npmjs.com/package/express-basic-auth , for implementing basic authentication in the BlogTutAPI server, cautions against timing attacks, https://en.wikipedia.org/wiki/Timing_attack and provides a 'safeCompare' function to protect against the timing attack. But safeCompare seems to be a straight string comparison function. My code uses bcrypt.compare. I browsed the net to see if bcrypt.compare is protected against timing attacks. Comments on this post: Is bcrypt.compare vulnerable to timing attack, https://stackoverflow.com/questions/35620979/is-bcrypt-compare-vulnerable-to-timing-attack , says it is protected.
========================================
30 Sep. 2024
Finished going through source code of PC project BlogTutAPI (yesterday 29 Sep. 2024).
Now am going through the React front end (PC project directory: cawv-cur) at an overview level. I don't want to get into details as I am quite confident that I can easily figure it out given the lot of work I have done over past months on Next.js and ReactJS for the Gita web app. However, the blog front end uses ReactJS React Router and easy-peasy (global) state management packages, and uses a useAxiosGet hook to provide pending state info. to the page component using it. Next.js handles these things differently and so I would like to refresh my knowledge about the earlier mentioned topics as used in the front end app.
React tutorial: blog app using easy-peasy, https://raviswdev.blogspot.com/2024/03/react-tutorial-blog-app-using-easy-peasy.html was helpful to figure out helpers part. Rest of easy-peasy usage in app was quite easy to understand after quick look at basic easy-peasy docs.
Notes on React Router, https://raviswdev.blogspot.com/2024/03/notes-on-react-router.html states, "https://www.freecodecamp.org/news/how-to-use-react-router-version-6/ uses JSX for Router related components (e.g. ..) and so is easier to follow than https://reactrouter.com/en/main/start/tutorial which uses method(s) (e.g. createBrowserRouter() method)." That was useful as in this refresh round I first went to the official tutorial and had to do some mapping of createBrowserRouter() method to BrowserRouter component used in the blog app. This article linked to in the same post was helpful to refresh my knowledge about Outlet and some other React Router features: "Nested routes, Outlet, Navigate and how to protect routes are covered in this text tutorial: How to use React Router v6 in React apps, https://blog.logrocket.com/react-router-v6-guide/ ."
Noted that blog app does not use protected routes feature. So going to http://localhost:3000/newpost even if user credentials are invalid, shows the page. But on clicking Create Post, one is taken to User page.
Blog app hides links that unauthorized user is not supposed to go to in its nav component.
I think I now have a decent understanding of how blog app uses React Router.
Finished going through the React front end source code but skipped some details like use of AbortController in useAxiosGet(). I have a good overview level (refreshed) knowledge about the code and that's enough for now.
======================
Deploying BlogTutAPI on free hosting platform
===================================
Checked out a few options from: Top free Heroku alternatives for every case!!!! Heroku बंद हुआ तो क्या हुआ 💪🏻💪🏻, https://www.youtube.com/watch?v=EyfSdyFkYRg which is where I had got the cyclic.sh option some months ago (probably in March 2024). Ref: Notes on Node Express tutorial Blog API deployment attempts and eventual successful deployment on Cyclic.sh, https://raviswdev.blogspot.com/2024/03/log-of-node-express-tutorial-blog-api.html , March 2024.
Tried back4app. No credit card needed but needs a docker file in the repo!
Tried Fly.io. Asks for credit card (in Pay As You Go plan which seems to be closes to free plan).
[Also tried Railway but tripped up at some point. Don't recall exactly where it was - probably credit card again.]
Tried render and it worked! Initially it asked for credit card info. when I tried deploy but I selected free plan (looks like by default it was a paid plan) and then it did not ask for credit card info. and proceeded with deployment.
https://blogtutapi.onrender.com/api/posts/ with basic authentication set in Postman works.
https://blogtutapi.onrender.com:10000/api/posts/ [It listens on port 10000. ... does NOT work.]
Dashboard: https://dashboard.render.com/
Changed API env. variable to https://blogtutapi.onrender.com/api/posts/ in ravisiyerblogfs on netlify and now the app: https://ravisiyerblogfs.netlify.app/ works with valid user/pwd specified for user.
==================
MongoDB seems to need daily login as a security measure. Ref: Allow me to stay logged in for a long period of time, https://feedback.mongodb.com/forums/924145-atlas/suggestions/40271953-allow-me-to-stay-logged-in-for-a-long-period-of-ti.
=================
I think that finishes the 3rd round stuff (on 30 Sep. 2024).
Comments
Post a Comment