Prerequisites (Must Know)
- Basic knowledge of JavaScript syntax
- Basics of React Syntax
- Fundamentals of Networking Concepts
Use a Generator called Vite
- Execute
npm create vite@latestin VSCode terminal
Mac:React Full Stack marygracezabala$ npm create vite@latest
> npx
> cva
│
◇ Project name:
│ front-end
│
◇ Select a framework:
│ React
│
◇ Select a variant:
│ TypeScript
│
◇ Scaffolding project in /Users/marygracezabala/Documents/React Full Stack/front-end...
│
└ Done. Now run:
cd front-end
npm install
npm run dev
npm notice
npm notice New major version of npm available! 10.8.1 -> 11.3.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.3.0
npm notice To update run: npm install -g npm@11.3.0
npm notice
Mac:React Full Stack marygracezabala$
2. Install all dependencies using npm install. Along them is react
Mac:React Full Stack marygracezabala$ cd front-end/
Mac:front-end marygracezabala$ npm install
added 181 packages, and audited 182 packages in 11s
43 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Mac:front-end marygracezabala$
3. Run npm run dev and access the site using http://localhost:5173
Mac:front-end marygracezabala$ npm run dev
VITE v6.2.6 ready in 279 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help4. We have a boiler plate in /src/App.tsx. If you update code, it will automatically be seen in the browser because of HMR
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
}
export default App
Create a Home Page
- Create a pages app in /src folder
- Create homepage.tsx
export default function HomePage() {
return (
<div>
<h1>Welcome to the HomePage</h1>
<p>This is the HomePage of our application.</p>
</div>
);
}3. In the main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)4. In the App.tsx
import './App.css'
import HomePage from './pages/HomePage'
function App() {
// const [count, setCount] = useState(0)
return (
<HomePage />
);
}
export default App
This is the result

Create Multiple Pages in the blog using Route
- We need to install the npm module react-router DOM; you can install it using
npm install react-router-dom@latest. I used the latest but its up to you what version you want to use.
Mac:front-end marygracezabala$ npm install react-router-dom@latest
added 7 packages, and audited 189 packages in 1s
43 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Mac:front-end marygracezabala$ 2. In the App.tsx import the createBrowserRouter and RouterProvider functions from the react-router-dom we installed
import {
createBrowserRouter,
RouterProvider,
} from 'react-router-dom';
Adding the routes and using the functions, we have the following updated script
import {
createBrowserRouter,
RouterProvider,
} from 'react-router-dom';
import './App.css'
import HomePage from './pages/HomePage.tsx';
import AboutPage from './pages/AboutPage.tsx';
import ArticlesListPage from './pages/ArticlesList.tsx';
import ArticlePage from './pages/ArticlePage.tsx';
const routes = [{
path:'/',
element:<HomePage />,
}, {
path:'/about',
element:< AboutPage />,
}, {
path: '/articleslist',
element: <ArticlesListPage />,
}, {
path: '/articles/individual',
element: <ArticlePage />,
}]
const router = createBrowserRouter(routes);
function App() {
// const [count, setCount] = useState(0)
return (
<RouterProvider router={router} />
);
}
export default App
Creating NavBar
- Go to
/srcand create a file named `Navbar.tsx` - WE can use href and anchor for referencing files, but for react we will use the Link module to link a directory for easier tasks. We need to import the Link from
react-router-dom.
Why use Link?
- Reacts are generally single-page applications, meaning that even our applications use multiple pages, it's just really javaScript logic behind the scenes.
- Now we don't need to reload our site fully as the anchor tag was designed to do it which we don't need in React Apps.
import { Link } from "react-router-dom";
export default function NavBar() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/articleslist">Articles</Link>
</li>
</ul>
</nav>
);
}3. After that, we need to create a layout for our site's NavBar. Under /src, create Layout.tsx. We will reference the NavBar and add a new module called Outlet which is also from module react-router-dom. Here is our script
The Layout component will act as the main wrapper for all our pages (like HomePage, AboutPage, etc.).
This is useful when you want shared elements such as a Navbar, Footer, or Sidebar to be visible across all pages.
import { Outlet} from "react-router-dom";
import NavBar from "./NavBar";
export default function Layout() {
return (
<>
<NavBar />
<Outlet />
</>
);
}4. Now we will add the Layout directory in our App.tsx. I added the following.
import Layout from './Layout.tsx';
Next, we update our routes array to implement nested routing.
We define a root path ('/') that uses the Layout component as the main layout.
Inside the children property, we specify the actual pages that should render inside the layout when users visit different URLs.
Here’s the updated routes:
const routes = [{
path: '/',
element: <Layout />,
children: [{
path:'/',
element:<HomePage />,
}, {
path:'/about',
element:< AboutPage />,
}, {
path: '/articleslist',
element: <ArticlesListPage />,
}, {
path: '/articles/individual',
element: <ArticlePage />,
}]
}]- The
Layoutcomponent now wraps all the child routes. - Each page (
HomePage,AboutPage, etc.) will render inside theOutletprovided byLayout.tsx. - This makes the app cleaner and avoids repeating common UI parts across pages
5. And then, we deleted the < NavBar /> in the function App()
Since the Navbar and shared layout are now handled inside the Layout component,
we no longer need to manually add <NavBar /> inside the App() function.
We simplify App() to only provide the RouterProvider:
function App() {
// const [count, setCount] = useState(0)
return (
<>
<RouterProvider router={router} />
</>
);
}The script will be:
import {
createBrowserRouter,
RouterProvider,
} from 'react-router-dom';
import './App.css'
import HomePage from './pages/HomePage.tsx';
import AboutPage from './pages/AboutPage.tsx';
import ArticlesListPage from './pages/ArticlesList.tsx';
import ArticlePage from './pages/ArticlePage.tsx';
import Layout from './Layout.tsx';
const routes = [{
path: '/',
element: <Layout />,
children: [{
path:'/',
element:<HomePage />,
}, {
path:'/about',
element:< AboutPage />,
}, {
path: '/articleslist',
element: <ArticlesListPage />,
}, {
path: '/articles/individual',
element: <ArticlePage />,
}]
}]
const router = createBrowserRouter(routes);
function App() {
// const [count, setCount] = useState(0)
return (
<>
<RouterProvider router={router} />
</>
);
}
export default App
Display ArticlePage and display Multiple Article Pages using that Page
- Got to
App.tsx. Now we modify from/articles/individualto/articles/:name- The
:nameis a URL or a route parameter. - Catch all routes that start with articles and have something else after them. Example
/articles/nameor/articles/124 - We can actually see the value of the name of the path and use it to load the appropriate article and display it in the component
const routes = [{ path: '/', element: <Layout />, children: [{ path:'/', element:<HomePage />, }, { path:'/about', element:< AboutPage />, }, { path: '/articleslist', element: <ArticlesListPage />, }, { path: '/articles/:name', //This is the name that will be use later by the useParams(), a built in function from react-router-dom element: <ArticlePage />, }] }]
- The
- In the
/src, create article-content.tsx to create a list for dictionary articles. Inside the article-content.tsx:
const articles = [
{
name: 'learn-react',
title: 'Learn React Faster',
content: [
'React is a JavaScript library for building user interfaces. It allows developers to create large web applications that can change data, without reloading the page. React is fast, scalable, and simple. It works only on user interfaces in web and mobile applications. This means that you will need to use additional libraries for state management, routing, and interaction with an API.',
'React is a JavaScript library for building user interfaces. It allows developers to create large web applications that can change data, without reloading the page. React is fast, scalable, and simple. It works only on user interfaces in web and mobile applications. This means that you will need to use additional libraries for state management, routing, and interaction with an API.'
]
},
{
name: 'learn-node',
title: 'Learn Node Faster',
content: [
'Node.js is a JavaScript runtime built on Chrome\'s V8 JavaScript engine. It is used to build scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js is perfect for data-intensive real-time applications that run across distributed devices.',
],
},
{
name: 'mongodb',
title: 'Learn MongoDB Faster',
content: [
'MongoDB is a document database, which means it stores data in JSON-like documents. This makes it easy to work with and understand. MongoDB is a NoSQL database, which means it does not use the traditional table-based relational database structure. Instead, it uses collections and documents. This allows for more flexibility and scalability.',
]
},
]
export default articles;Don't forget to export it so we can reuse/reimport it in ArticlePage.tsx file
3. Now inside the ArticlePage, import first the article content using import articles from '../article-content'. Then we can use the articles in our function ArticlePage().
First create a const name. To create it use the useParams which has the dictionary of the name value
//long method
param = useParams()
name = param.name
// single line
const { name } = useParams() //where it directlysaves the name value inside the name; example http://localhost/article/learn-react; the learn-react will be saved into the name const
Now declare const article which will for loop with each of the article's name and check if it matched with the const name we declared previously:
const article = articles.find(
a => a.name === name
);where
articles.find - find articles
a => "a" - is a temporary variable we use to for loop to each article
a.name - accessing the name key inside the "a" article
a.name === name - if a.name match with the name const, then it will stop as it already found the article dictionaryNow we will return the ArticlePage value. This will be the display in our html page
return (
<>
<div>
<h1>{article.title}</h1>
{article.content.map(p => <p key={p}>{p}</p>)}
</div>
</>
);where:
article.title - is the title of the article;
article.content.map(p => <p key={p}>{p}</p>) - map and checks each content where:
<p - Open a paragraph tag
key={p} - Tell React: "This paragraph is unique by this key"
> - Close the opening tag
{p} - Insert the text of the paragraph inside
</p> -Close the paragraph tag
The whole script will be
import { useParams } from 'react-router-dom';
import articles from '../article-content';
export default function ArticlePage() {
const { name } = useParams();
const article = articles.find(
a => a.name === name
);
return (
<>
<div>
<h1>{article.title}</h1>
{article.content.map(p => <p key={p}>{p}</p>)}
</div>
</>
);
}The resulting page will be

Creating List of articles in ArticlesListPage
- First, import the articles data from
article-content.tsand theLinkcomponent fromreact-router-dom.import articles from "../article-content"; import { Link } from "react-router-dom";
- Setting up the
ArticlesListPageComponentexport default function ArticlesListPage() { return ( <> <h1>Articles</h1> {articles.map(a => ( <Link key={a.name} to={`/articles/${a.name}`}> <h3>{a.title}</h3> <p>{a.content[0].substring(0, 150)}...</p> </Link> ))} </> ); }Part What it Does <h1>Articles</h1>Displays a heading for the page articles.map(a => (...))Loops through each article ( a) in thearticlesarray<Link>Wraps each article to make it clickable and navigate to the article’s own page key={a.name}Provides a unique key for each link (required by React when rendering lists) to={'/articles/' + a.name}Builds the URL path to the specific article page <h3>{a.title}</h3>Displays the article’s title <p>{a.content[0].substring(0,150)}...</p>Displays the first 150 characters of the first paragraph of the article’s content
- Here is the script
import articles from "../article-content";
import { Link } from "react-router-dom";
//import ArticlesList from "../ArticlesList";
export default function ArticlesListPage() {
return (
<>
<h1>Articles</h1>
{articles.map(a => (
<Link key={a.name} to={'/articles/' + a.name}>
<h3>{a.title}</h3>
<p>{a.content[0].substring(0,150)}</p>
</Link>
))}
</>
);
}
//<ArticlesList articles={articles} />
Now we see the list of articles and configured link to their specific location


Creating Separate Popular Article List in our HomePage
- Create a new file in the
/srccalledArticlesList.tsx. - Import Link module
- Create function
ArticlesList (articles). It will pass whatever articles it want to pass. - Add again the article.map for loop to add the articles. You can modify it accordingly what article you wanted to show:
{articles.map(a => ( <Link key={a.name} to={'/articles/' + a.name}> <h3>{a.title}</h3> <p>{a.content[0].substring(0,150)}</p> </Link> ))}
- The ending script of ArticlesList.tsx will be
import { Link } from "react-router-dom" export default function ArticlesList( {articles} ) { return ( <> {articles.map(a => ( <Link key={a.name} to={'/articles/' + a.name}> <h3>{a.title}</h3> <p>{a.content[0].substring(0,150)}</p> </Link> ))} </> ) }
- Now go to ArticlesListPage.tsx and modify it
- Remove the Link module
import{Link}from"react-router-dom";as we will now just import the content from../ArticlesList tsxfile that we created - Add the ArticlesList so we can show the articles list there
import articles from "../article-content"; //import { Link } from "react-router-dom"; we will use the ArticlesList component instead import ArticlesList from "../ArticlesList";
- Remove the Link module
- Since we will now not be using Link module here and will just output the content from ArticlesList, we will remove the Link and map loop
import articles from "../article-content"; //import { Link } from "react-router-dom"; we will use the ArticlesList component instead import ArticlesList from "../ArticlesList"; export default function ArticlesListPage() { return ( <> <h1>Articles</h1> <ArticlesList articles={articles} /> </> ); } //Removing the code below because we are using the ArticlesList component instead // {articles.map(a => ( // <Link key={a.name} to={'/articles/' + a.name}> // <h3>{a.title}</h3> // <p>{a.content[0].substring(0,150)}</p> // </Link> // ))}
| Part | What Happens |
|---|---|
import articles | Import the articles array |
import ArticlesList | Import the list-rendering component |
<ArticlesList articles={articles} /> | Call the function ArticlesList and pass the articles array as a prop |
When we write articles={articles},
- The left side
articlesis the prop name theArticlesListexpects. - The right side
articlesis the variable we imported.
This way, ArticlesList receives the data and maps over it to render the clickable article list.
Summary: "ArticlesListPage imports the articles array and passes it as a prop to ArticlesList.ArticlesList receives the articles prop, maps over the array, and displays a clickable list of article titles and content previews."
Final code modification
ArticlesList.tsx
import { Link } from "react-router-dom";
export default function ArticlesList({ articles }) {
return (
<>
{articles.map(a => (
<Link key={a.name} to={`/articles/${a.name}`}>
<h3>{a.title}</h3>
<p>{a.content[0].substring(0, 150)}...</p>
</Link>
))}
</>
);
}ArticlesListPage.tsx
import articles from "../article-content";
import ArticlesList from "../ArticlesList";
export default function ArticlesListPage() {
return (
<>
<h1>Articles</h1>
<ArticlesList articles={articles} />
</>
);
}Sample Output

Creating a 404 Page in React
When to use it?
- When users go to a route that was not declared in the code
How to do it?
- Go to App.tsx and add errorElement when there is problem displaying a route
- Add a new page NotFoundPage.tsx in pages directory. We will add this code.
export default function NotFoundPage() { return ( <> <h1>Error 404! Page Not Found</h1> <p>Sorry, this page does not exist.</p> </> ) }
- Then we will now add it in App.tsx
import { createBrowserRouter, RouterProvider, } from 'react-router-dom'; import './App.css' import HomePage from './pages/HomePage.tsx'; import AboutPage from './pages/AboutPage.tsx'; import ArticlesListPage from './pages/ArticlesListPage.tsx'; import ArticlePage from './pages/ArticlePage.tsx'; import Layout from './Layout.tsx'; import NotFoundPage from './pages/NotFoundPage.tsx'; const routes = [{ path: '/', element: <Layout />, errorElement: < NotFoundPage />, children: [{ path:'/', element:<HomePage />, }, { path:'/about', element:< AboutPage />, }, { path: '/articleslist', element: <ArticlesListPage />, }, { path: '/articles/:name', element: <ArticlePage />, }] }] const router = createBrowserRouter(routes); function App() { // const [count, setCount] = useState(0) return ( <> <RouterProvider router={router} /> </> ); } export default App
- For example we access a path that was not defined, here is the result

Adding Styles
Now in styles, we modified the index.css and App.css
Here's the relevant structure:
/src
|-- main.tsx
|-- App.tsx
|-- index.css
|-- App.css
- index.css - it is the Global stylesheet, foundational and base layer design — setting up fonts, colors, and spacing that all components will inherit.
Where it is referenced?
It was referenced in main.tsx. Please see below
// main.tsx import './index.css';The
index.cssfile is imported at the entry point of your app (main.tsx). This means that its styles are loaded globally across your entire React application.- The code we used for the index.css was referenced in github -> https://github.com/grace188031/react-blog/blob/chapter1-basic-css-design/front-end/src/index.css
- App.css - It is the style of the App component
Where it is referenced?
// App.tsx import './App.css';This file is imported inside your App component, making it available when the
Appcomponent is rendered.- It usually handles layout or container-specific styling, especially for the root element (
#root) into which the entire React app is rendered. Example code in App.css
#root { max-width: 800px; margin: 0 auto; padding: 2rem; }As you see above, the App.css added the design in the root container. The root container was referenced in the index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React + TS</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
As you see here:

Setting up Backend NodeJS and Express Server
Now I will be setting up the backend server that will be using typescript. I will follow the procedure in https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript
Create back-end directory folder. Its a directory outside the frontend directory. Then initialize the npm to create package.json
marygracezabala@Mac React Full Stack % git checkout -b CH2-Setting-Express_Server Switched to a new branch 'CH2-Setting-Express_Server' marygracezabala@Mac React Full Stack % git branch * CH2-Setting-Express_Server chapter-1 chapter1-basic-css-design main marygracezabala@Mac React Full Stack % mkdir back-end marygracezabala@Mac React Full Stack % cd back-end marygracezabala@Mac back-end % npm init -y Wrote to /Users/marygracezabala/Documents/React Full Stack/back-end/package.json: { "name": "back-end", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "description": "" }Install typescript and @types/express
marygracezabala@Mac back-end % npm install --save-dev typescript added 1 package, and audited 2 packages in 788ms found 0 vulnerabilities marygracezabala@Mac back-end % nano tsconfig.json marygracezabala@Mac back-end % npm install express @types/express added 78 packages, and audited 80 packages in 2s 14 packages are looking for funding run `npm fund` for details found 0 vulnerabilities- Under backend directory, create src directory
marygracezabala@Mac back-end % mkdir src - Now create the typescript configuration under src directory
marygracezabala@Mac back-end % nano src/server.ts Run the typescript compiler to javascript files
marygracezabala@Mac back-end % npx tscRun the file
Server.ts configuration
import express from 'express'; const app = express(); const port = 8000; app.get('/hello', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { return console.log(`Express is listening at http://localhost:${port}`); });Run it
marygracezabala@Mac back-end % node dist/server.js Express is listening at http://localhost:8000'Here is the result

Now that its running, we can add ESlint functionality for our tyoescript to check if there are erros in our script
marygracezabala@Mac back-end % npm install --save-dev eslint added 85 packages, and audited 165 packages in 2s 36 packages are looking for funding run `npm fund` for details found 0 vulnerabilities marygracezabala@Mac back-end % npm init @eslint/config@latest > back-end@1.0.0 npx > create-config @eslint/create-config: v1.8.1 ✔ What do you want to lint? · javascript, json, jsonc, json5 ✔ How would you like to use ESLint? · problems ✔ What type of modules does your project use? · esm ✔ Which framework does your project use? · none ✔ Does your project use TypeScript? · no / yes ✔ Where does your code run? · browser, node The config that you've selected requires the following dependencies: eslint, @eslint/js, globals, typescript-eslint, @eslint/json ✔ Would you like to install them now? · No / Yes ✔ Which package manager do you want to use? · npm ☕️Installing... up to date, audited 198 packages in 559ms 50 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Successfully created /Users/marygracezabala/Documents/React Full Stack/back-end/eslint.config.mjs file. marygracezabala@Mac back-end % npm install tsx added 5 packages, and audited 203 packages in 2s 52 packages are looking for funding run `npm fund` for details found 0 vulnerabilitiesNow run to check errors in our script
marygracezabala@Mac back-end % npx eslint . --ext .ts (node:16122) ESLintIgnoreWarning: The ".eslintignore" file is no longer supported. Switch to using the "ignores" property in "eslint.config.js": https://eslint.org/docs/latest/use/configure/migration-guide#ignoring-files (Use `node --trace-warnings ...` to show where the warning was created) /Users/marygracezabala/Documents/React Full Stack/back-end/dist/server.js 6:35 error A `require()` style import is forbidden @typescript-eslint/no-require-imports /Users/marygracezabala/Documents/React Full Stack/back-end/package-lock.json 7:5 error Empty key found json/no-empty-keys ✖ 2 problems (2 errors, 0 warnings)You must add ignore configuration in eslint.config.mjs for dist/*, node-module/** and package-lock.json files because those are generated scripts and not needed to be checked for errors. Please see below
export default defineConfig([ // 🔽 1. Ignore folders and files you don't want to lint { ignores: ["dist/**", "node_modules/**", "package-lock.json"], },As you see errorrs are gone when you execute it
marygracezabala@Mac back-end % npx eslint . --ext .ts marygracezabala@Mac back-end % npx eslint . --ext .tsNow update the package.json file. It can be useful to put your commonly run command line tasks into npm scripts. npm scripts are defined in your
package.jsonfile and can be run with the commandnpm run your_script_name.In this step, you will add a
startscript that will transpile the TypeScript code and then run the resulting.jsapplication.You will also add a
lintscript to run the eslint linter on your TypeScript files.Open the
package.jsonfile and update it accordingly:
How to fix your tsconfig.json to output ESM
I search that modern nodejs uses ESM instead of commonjs. I search how to output ESM instead. Here is what chatgpt answered
- Replace the tsconfig.json like this
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}2. Update package.json to use "type":module". It should look like this
{
"name": "back-end",
"version": "1.0.0",
"main": "dist/app.js",
"type": "module",
"scripts": {
"start": "tsc && node dist/server.js",
"dev": "tsx watch src/server.ts",
"build": "tsc",
"lint": "eslint . --ext .ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@eslint/js": "^9.24.0",
"@eslint/json": "^0.11.0",
"eslint": "^9.24.0",
"globals": "^16.0.0",
"typescript": "^5.8.3",
"typescript-eslint": "^8.30.1"
},
"dependencies": {
"@types/express": "^5.0.1",
"express": "^5.1.0"
}
}
3. Fix your imports (if needed)
With "module": "ESNext" and "type": "module", you must:
- Use
import express from 'express' - Add
.jsfile extensions when importing local files:
// ✅ Correct in ESM import { something } from './utils.js'; // even though the file is utils.ts
TypeScript will compile utils.ts ➜ utils.js and the import will still work in Node.
4. Clean and rebuild it
marygracezabala@Mac back-end % rm -rf dist/
marygracezabala@Mac back-end % npx tsc
marygracezabala@Mac back-end % node dist/server.js
Express is listening at http://localhost:8000
Testing Express Server with Postman
Download Postman and send GET traffic request

- Can also send POST and other HTTP methods. As we didnt configured POSY in our script, it will be error
Configure post request like this
import express from 'express'; const app = express(); const port = 8000; app.get('/hello', (req, res) => { res.send('Hello from a GET Engdpoint!'); }); app.post('/hello', (req, res) => { res.send('Hello from a POST Endpoint!'); }); app.listen(port, () => { return console.log(`Express is listening at http://localhost:${port}`); });Our POSt has auto restart whenever there are changes because we installed tsx and configured our scripts like this in package.json. IF we didnt configured it we need to manually stop the node server, run compiler
npx tsc, then run the backend server again.{ "name": "back-end", "version": "1.0.0", "main": "dist/app.js", "type": "module", "scripts": { "start": "tsc && node dist/server.js", "dev": "tsx watch src/server.ts", "build": "tsc", "lint": "eslint . --ext .ts", "test": "echo \"Error: no test specified\" && exit 1" },Checking the result:

- Allow endpoint to have access to request body. To do this, add the following script and save
app.use(express.json());
app.post('/hello', (req, res) => {
res.send(`Hello, ${req.body.name} from a POST Endpoint!`);
});Then, test it, adding body request which is in JSON format.

Route Parameters in Express
Aside from extracting the name value from the ${req.body.name}, we can use params value to extract the value we set in the url. Example if we set it like curl -X http://localhost:8000/hello/grace, we can extract grace using ${req.params.name}
Configure the server.ts script
app.post('/hello/:firstname', (req, res) => { res.send(`Hello, ${req.params.firstname} from a POST Endpoint!`); });- Here is the result

Create Upvote Articles
Now we will set configure upvote logic in our code to check what articles are most liked by the people. I will create a new branch in my git to separate the branches
Mac:React Full Stack marygracezabala$ git checkout -b CH2-Express-NodeJS-UpvoteArticles
Switched to a new branch 'CH2-Express-NodeJS-UpvoteArticles'
Mac:React Full Stack marygracezabala$ git branch
* CH2-Express-NodeJS-UpvoteArticlesTrack upvotes and comments:
Since we dont have a database yet to track votes, we will create an array list to store inmemory database. This will not persist after node server restarted as its not a real database
const articleInfo = [ { articleName: 'learn-node', upvotes: 0}, { articleName: 'learn-react', upvotes: 0}, { articleName: 'mongodb', upvotes: 0}, ]Then add the following code to add upvote for every invoked POST request
import express from 'express'; const app = express(); const port = 8000; const articleInfo = [ { articleName: 'learn-node', upvotes: 0}, { articleName: 'learn-react', upvotes: 0}, { articleName: 'mongodb', upvotes: 0}, ] app.use(express.json()); app.post('/api/articles/:articleName/upvote', (req, res) => { const article = articleInfo.find(a => a.articleName === req.params.articleName); article.upvotes += 1; res.send(`The article with the name: ${req.params.articleName} now has ${article.upvotes} upvotes!`); }); // We can also use this syntax for upvote // app.post('/api/articles/:articleName/upvote', (req, res) => { // const { articleName } = req.params; // const article = articleInfo.find(a => a.articleName === articleName); // article.upvotes += 1; // res.send(`The article with the name: ${articleName} now has ${article.upvotes} upvotes!`); // }); app.listen(port, () => { return console.log(`Express is listening at http://localhost:${port}`); });- Create a POSt request that takes the request.param.name. Here is the result

Adding Comments
Add comments key pair dictionary in our array:
const articleInfo = [ { articleName: 'learn-node', upvotes: 0, comments: [] }, { articleName: 'learn-react', upvotes: 0, comments: [] }, { articleName: 'mongodb', upvotes: 0, comments: [] }, ]Add another endpoint for adding comments
app.post('/api/articles/:articleName/comments', (req,res) => { const { articleName } = req.params; const { postedBy, text } = req.body; const article = articleInfo.find(a => a.articlename === articleName); article.push({ postedBY, text, }); res.json(article); });I also changed the upvote config response to res.json(article) so the POST return the json details everytime I vote. Here are the results
Invoking Comment POST

Invoking upvote POST

Adding MongoDB in our site to Persist our Data
Features
- Non-relational (stores JSON-like data)
- No need to learn SQL
- open-source and easy to use
Downloading and Installing MongoDB
- Download the installer MongoDB COmmunity Edition. Choose your OS here (https://www.mongodb.com/docs/manual/installation/)
Ths installation includes the following
The installation includes the following binaries:
After installation execute
marygracezabala@Mac React Full Stack % brew services start mongodb-community@8.0to start the service. You can also usemarygracezabala@Mac React Full Stack % mongod. Then in another tab, execute mongosh to connect to the running service. Here are their difference:
| Command | Behavior | Startup | Shutdown | Use Case |
|---|---|---|---|---|
mongod --dbpath ~/mongodb-data (create path first mkdir -p ~/mongodb-data) | Manual server in terminal window | Manual | Close terminal or Ctrl+C | Quick tests, temp DB |
brew services start mongodb... | Background service with launchd | Auto | brew services stop | Persistent dev DB server |
4. Connect to mongodb now using mongosh. You can see that you are now inside the shell of mongodb. The default db is test which is useful for testing; however I want to test using my own database; hence I will be creating new database.
For creating new database execute:
test> use full-stack-react-db
switched to db full-stack-react-db
full-stack-react-db>
Here are the complete commands I executed
Mac:React Full Stack marygracezabala$ mongosh
Current Mongosh Log ID: 67fff783b613e1c2b5c1a0e0
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.5.0
Using MongoDB: 8.0.8
Using Mongosh: 2.5.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2025-04-16T14:31:26.418-04:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
test> use full-stack-react-db
switched to db full-stack-react-db
full-stack-react-db>
5. After that, we can now load data to our database full-stack-react-db using:
db.articles.insertMany([
... { articleName: 'learn-node', upvotes: 0, comments: [] },
... { articleName: 'learn-react', upvotes: 0, comments: [] },
... { articleName: 'mongodb', upvotes: 0, comments: [] },
... ])We just added our array to the full-stack-react-db and is now ready to be called by the endpoint. By the way, these data are called collections(of related or similar items) which is knows as tables in SQL databases.
full-stack-react-db> db.articles.insertMany([
... { articleName: 'learn-node', upvotes: 0, comments: [] },
... { articleName: 'learn-react', upvotes: 0, comments: [] },
... { articleName: 'mongodb', upvotes: 0, comments: [] },
... ])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('67fffc8eb613e1c2b5c1a0e1'),
'1': ObjectId('67fffc8eb613e1c2b5c1a0e2'),
'2': ObjectId('67fffc8eb613e1c2b5c1a0e3')
}
}6. To check the items inside our collections, execute db.articles.find({}).pretty()
full-stack-react-db> db.articles.find({}).pretty()
[
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e1'),
articleName: 'learn-node',
upvotes: 0,
comments: []
},
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e2'),
articleName: 'learn-react',
upvotes: 0,
comments: []
},
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e3'),
articleName: 'mongodb',
upvotes: 0,
comments: []
}
]
Other mongodb commands that can be run in the shell:
- Find a single item
db.articles.findOne( { 'articleName':'learn-node'} ):
full-stack-react-db> db.articles.findOne( { 'articleName':'learn-node'} )
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e1'),
articleName: 'learn-node',
upvotes: 0,
comments: []
}
full-stack-react-db> 2. Multiple Items that match a given criteria for example finding articles with upvote: 0
full-stack-react-db> db.articles.find( { 'upvotes':0 } )
[
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e1'),
articleName: 'learn-node',
upvotes: 0,
comments: []
},
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e2'),
articleName: 'learn-react',
upvotes: 0,
comments: []
},
{
_id: ObjectId('67fffc8eb613e1c2b5c1a0e3'),
articleName: 'mongodb',
upvotes: 0,
comments: []
}
]
Adding MongoDB to Express
Install mongodb package into our project. This will allow our mongodb to connect inside our nodejs server
$ npm install mongodb added 12 packages, and audited 13 packages in 1s found 0 vulnerabilities Mac:React Full Stack marygracezabala$Now in the
/backend/src/server.ts, add the following:
import { MongoClient,ServerApiVersion } from 'mongodb';
app.get('/api/articles/:articleName', async (req, res) => {
const { articleName } = req.params;
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
await client.connect();
const db = client.db('full-stack-react-db');
const article = await db.collection('articles').findOne({ articleName } );
res.json(article);
});
What does the script do?
1. Import the MongoDB client
import { MongoClient, ServerApiVersion } from 'mongodb';
MongoClient: the main way to connect to and query a MongoDB database.ServerApiVersion.v1: ensures compatibility and future-proofing for the API.
2. Create the GET route
app.get('/api/articles/:articleName', async (req, res) => {
- This sets up an Express GET endpoint at
/api/articles/:articleName. The
:articleNamepart is a route parameter, meaning we can pass dynamic article names in the URL like:http://localhost:8000/api/articles/learn-react
3. Extract the articleName from the URL
const { articleName } = req.params;
- This line pulls
articleNamedirectly from the URL using destructuring. - For example, if the URL is
/api/articles/learn-react, thenarticleName = "learn-react".
4. Define the MongoDB connection URI and client
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
127.0.0.1:27017is the localhost address where MongoDB is running.- The
MongoClientis initialized with best practices:strict: trueensures only defined commands are used.deprecationErrors: truegives warnings if you’re using outdated MongoDB features.
5. Connect to the MongoDB server
await client.connect();
- This line opens the connection to MongoDB before performing any queries.
- Since it’s
await, this route must beasync.
6. Access the database and collection
const db = client.db('full-stack-react-db');
const article = await db.collection('articles').findOne({ articleName });
- We access the
full-stack-react-dbdatabase. - Then, from the
articlescollection, we usefindOne()to find a document with a matchingarticleName.
7. Send the result back to the client
res.json(article);
- This sends the article as a JSON response.
- If no match is found, it will return
null.
Example Output
GET /api/articles/learn-react
Response:

Rewriting the upvote endpoint to use MongoDB
Github Link
First, we dont want to always connect the database whnever we get the details of specific article, upvote an article or add a comment. Hence we created a functions that connects the database at the start so our endpoints can use it. Here is our function.
let db; async function connectToDB() { const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } }); await client.connect(); db = client.db('full-stack-react-db'); }We declared an external variable first
let dbThen we created a function and stored the client database instance to db ->
db = client.db('full-stack-react-db');- Then, we also create another function
start()so that before we start our backend node express server, we're triggering the functionconnectDB()first.- Wait for MongoDB to connect
- THEN start Express
Handle requests only after everything is ready
async function start() { await connectToDB(); app.listen(port, () => { return console.log(`Express is listening at http://localhost:${port}`); }); } start();
Then, we use the db instance to find and filter specific articles collection. We modified the upvote and get article function
app.post('/api/articles/:articleName/upvote', async (req, res) => { const { articleName } = req.params; const updatedArticle = await db.collection('articles').findOneAndUpdate({articleName }, { $inc: { upvotes: 1 } }, { returnDocument: 'after', }); res.json(updatedArticle); }); app.get('/api/articles/:articleName', async (req, res) => { const { articleName } = req.params; const article = await db.collection('articles').findOne({ articleName } ); res.json(article); });- Our updated script is in Link
Rewriting the comments endpoint to use MongoDB
Here is the syntax for adding new comment
app.post('/api/articles/:articleName/comments', async (req, res) => { const { articleName } = req.params; const { postedBy, text } = req.body; const newComment = { postedBy, text }; const updatedComment = await db.collection('articles').findOneAndUpdate({ articleName }, { $push: { comments: newComment } }, { returnDocument: 'after', }); res.json(updatedComment); });
Connecting the Front-End and back-End
Install Axios in the front end directory
Mac:front-end marygracezabala$ npm install axios added 23 packages, and audited 212 packages in 950ms 49 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Mac:front-end marygracezabala$
Loading data for React Router
- Specify another property called loader in App.tsx.
Add loader in the ArticlePage path
/articles/:name.loader: async function() { // await axios.get('http://localhost:8000/api/articles/:name') const response = await axios.get('/api/articles/learn-node'); const { upvotes, comments } = response.data; return { upvotes, comments };Import axios since you used it to call the backend api endpoint
import axios from 'axios';
Using the useLoaderData hook
- In the ArticlePage, import the useLoaderData to load to get the loader data we configured in App.tsx. Store it in the const, then add html paragraph <p></p> to display the result Upvote value.
Here, I addedd the userLoaderData
import { useParams, useLoaderData } from 'react-router-dom';Here is the html content displaying the upvotes
Declare const to store the useLoaderData()
const { upvotes,comments } = useLoaderData();Add html to call the const
{ upvotes,comments }<p>This article has Upvotes: {upvotes}</p>Here is the result of
https://localhost:5173/articles/learn-react. It has an error code 304.
In our React component, we tried fetching an article like this:
const response = await axios.get('/api/articles/learn-node');But in the browser console, we saw:
CORS policy: No 'Access-Control-Allow-Origin' header is present...We just see a status 304 Not Modified, with no article content showing.CORS stands for Cross-Origin Resource Sharing.
It’s a security feature implemented by browsers to prevent unauthorized access from one domain (or port) to another.If your frontend (React app) runs on
http://localhost:5173, and your backend (API) runs onhttp://localhost:8000, the browser sees them as different origins. Even though both are onlocalhost, they have different ports, so the browser blocks the request — unless explicitly allowed.To solve the issue, we need to set proxy in vite.config.ts. It can trick the browser by telling Vite to proxy
/apirequests to the backend server.import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vite.dev/config/ export default defineConfig({ plugins: [react()], //add the following to solve the CORS issue server: { proxy: { '/api': { target: 'http://localhost:8000', changeOrigin: true } } } })- Any request to
/apion the frontend (like/api/articles/learn-node) - Will be forwarded internally by Vite to
http://localhost:8000/api/articles/learn-node - This keeps it within the same origin from the browser’s point of view — no more CORS problem!
- Any request to
After we set the proxy, upvote number is now showing.

Using route parameters in loaders
Replace the hardcoded parameters in our route parameters. The code below was hard coded because it specifically hard coded learn-node instead of name or id parameter.
const response = await axios.get('/api/articles/learn-node');To make it flexible, add params to our function
loader: async function({ params }) { // call the params.name const response = await axios.get('/api/articles/' + params.name);- To make the loaders more modular, it better to export them as part of the page files. Hence we will move the async loader function to ArticlePages.tsx and then export it so App.tsx can call and use it.
Modifying and adding configuration in ArticlePages.tsx
import axios from 'axios'; // Create and export loader function and call the params.name export async function loader({ params }) { const response = await axios.get('/api/articles/' + params.name); const { upvotes, comments } = response.data; return { upvotes, comments }; }Then in App.tsx we import the loader as articleLoader and call the imported function in our routes
importArticlePage, {loaderasarticleLoader}from'./pages/ArticlePage.tsx';Then we added the articleLoader in the route
path: '/articles/:name', element: <ArticlePage />, // add the articleLoader function to the route loader: articleLoader
Displaying comments in our FrontEnd
Build a new component to display our comments in the
srcdirectory called CommentsList.tsxexport default function CommentsList( {comments} ) { return ( <> {comments.map(comment => ( <div key={comment.txt}> <h4>{comment.postedBy}</h4> <p>{comment.text}</p> </div> ))} </> ) }- Then import the function to the ArticlePage where you will output the comments for each article.
First import the function
importCommentsListfrom'../CommentsList';Export the comments
export default function ArticlePage() { const { name } = useParams(); const { upvotes, comments } = useLoaderData();Return the CommentsList with prop comment to the html display page of ArticlePage
return ( <> <div> <h1>{article.title}</h1> <p>This article has Upvotes: {upvotes}</p> {article.content.map(p => <p key={p}>{p}</p>)} < CommentsList comments={comments} /> </div> </> ); }
- Here is the result

Creating an Upvote Button
Import the
useStatehookimport { useState } from 'react';- This line imports a special tool from React called
useState. useStatehelps your component remember values — like scores, counters, or user input.- In your case, you use it to track the number of upvotes on the screen.
- Think of
useStateas a built-in memory slot for React components.
- This line imports a special tool from React called
Setup State and Upvote Function
const [upvotes, setUpvotes] = useState(initialUpvotes); async function onUpvoteClicked() { const response = await axios.post('/api/articles/' + name + '/upvote'); const updatedArticleData = response.data; setUpvotes(updatedArticleData.upvotes); }useState(initialUpvotes)initializes the number of upvotes.onUpvoteClicked():- Sends a POST request to your backend.
- Receives the updated data.
- Updates the UI using
setUpvotes(...).
Connect It to the Button
<div> <h1>{article.title}</h1> <button onClick={ onUpvoteClicked }>Upvote</button> ... </div>- Now when a user clicks this button:
onUpvoteClicked()runs- The backend adds 1 upvote
- The frontend updates to show the new total
- Notes:
File Responsibility React Frontend Shows upvotes and sends update via axios Express Backend Receives the POST request and updates MongoDB MongoDB Stores article data, including the upvotes count
Here is the resultV

Creating an add comment form
Create AddCommentForm.tsx in src
import { useState } from "react" export default function AddCommentForm( { onAddComment }) { const [nameText, setNameText] = useState(""); const [commentText, setCommentText] = useState(""); return ( <div> <h3>Add a comment</h3> <label htmlFor="nameText"> Name:</label> <input id="nameText" value={nameText} type="text" name="name" onChange={ e => setNameText(e.target.value)}/> <label htmlFor="commentText"> Comment:</label> <textarea id="commentText" value={commentText} name="text" onChange={ e => setCommentText(e.target.value)} /> <button onClick={() => { onAddComment( {nameText, commentText} ) ; setNameText(""); setCommentText(""); }}> Add Comment </button> </div> ) }- In Articlepage.tsx, we added the following
import AddCommentForm from '../AddCommentForm';const { upvotes: initialUpvotes, comments: initialComments } = useLoaderData();const [comments, setComments] = useState(initialComments);Added async function
async function onAddComment( {nameText, commentText} ) { const response = await axios.post('/api/articles/' + name + '/comments', { postedBy: nameText, text: commentText, }); const updatedArticleData = response.data; setComments(updatedArticleData.comments); }Added the comment form in html page
<AddCommentForm onAddComment={onAddComment} />
Clear the input textbox after adding a comment.
- The result

Adding User Authentication with Firebase Auth
Add authentication so that user's can't vote unless they are not login
Firebase Auth Provider
- Go to https://firebase.google.com/products/auth
- Go to console
Get started with Firebase Project

Add name for the project. I named mine as 'Full Stack React", then click Continue.

Adding Firebase Authentication to React
Add an app to our project. Click
</>button
Add name to your App then Register

It will give us a code and instruction to run it in our project.

Integrate Firebase Authentication
- To integrate Firebase authentication, I first installed the Firebase SDK into my React app front end:
cd frontendnpm install firebaseAfter running the command, the terminal confirmed:
added 82 packages, and audited 294 packages in 7s 51 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
Go to main.tsx and copy the block of code code to connect to firebase to check if user was authenticated.

- Create LoginPage.tsx and CreateAccountPage.tsx in /src/pages. I added initial configuration to the pages.
LoginPage.tsx
export default function CreateAccountPage() { return ( <h1>Log In</h1> ); }CreateAccountPage.tsx
export default function CreateAccountPage() { return ( <h1>Create Account</h1> ); }Then in App.tsx, add routes in our react router
const routes = [{ children: [{ ....... ....... }, { path: '/login', element: <LoginPage /> }, { path: '/create-account', element: <CreateAccountPage /> }] }]
Here is the result

Build Login Form
Here is the script for building LoginPage.tsx:
import { useState } from 'react' ; import { Link,useNavigate } from 'react-router-dom'; import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; export default function LoginPage() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); async function logIn() { try { await signInWithEmailAndPassword(getAuth(), email, password); useNavigate('/'); // Redirect to home page after successful login } catch (e) { setError(e.message); } } return ( <> <h1>Log In</h1> {error && <p>{error}</p>} <input type="email" placeholder="Your email address" value={email} onChange={e => setEmail(e.target.value)}/> <input type="password" value={password} placeholder="Your password" onChange={e => setPassword(e.target.value)}/> <button onClick={logIn}>Log In</button> <Link to="/create-account">Don't have an account? Create one here</Link> </> ); }
Create Account Page
Here is the script for createAccount.
import { useState } from 'react' ; import { Link,useNavigate } from 'react-router-dom'; import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth'; export default function CreateAccountPage() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [error, setError] = useState(''); const navigate = useNavigate(); async function createAccount() { if (password !== confirmPassword) { setError('Passwords do not match'); return; } try { await createUserWithEmailAndPassword(getAuth(), email, password); navigate('/articleslist'); // Redirect to home page after successful login } catch (e) { setError(e.message); } } return ( <> <h1>Create Account</h1> {error && <p>{error}</p>} <input type="email" placeholder="Your email address" value={email} onChange={e => setEmail(e.target.value)}/> <input type="password" value={password} placeholder="Your password" onChange={e => setPassword(e.target.value)}/> <input type="password" value={confirmPassword} placeholder="Confirm your password" onChange={e => setConfirmPassword(e.target.value)}/> <button onClick={createAccount}>Create Account</button> <Link to="/login">Already have an Account? Log In</Link> </> ); }Tested it but not working because I did not yet setup the firebase console

- Go to Firebase Console and set it up
- First check what kind of authentication you wish to allow
You can choose other authentication method, but for now I will select "Email and Password".

Create account has an error earlier because we did not turned it on in console. Please see below image

- After that, we were able to create and account and login the http://localhost:5173/articleslist. The email address and User UID was recorded in the firebase as seen in the image below.

Adding Logout in User Interface
In this activity, we will add logic that once the user was login in our app, there will be an option to log out. On the other hand, if its not yet login, we will add login button in the Navbar.tsx.
- Here is the configuration for Navbar.tsx:
We added
import { getAuth,signOut } from "firebase/auth"; import { useNavigate } from "react-router-dom";- Then we added current status
const isLoggedIn = true;just to test our logout functionality, the email I set for testing was"grace@gmail.com" - I added navigate which uses the function useNavigate from react-router-dom ->
const navigate = useNavigate(); And lastly, I added the LogIn and LogOut logic in the navbar list.
{isLoggedIn && ( <li style={{ color: 'white'}}> Logged in as {email} </li> )} <li> {isLoggedIn ? <button onClick={() => signOut(getAuth())}>Sign Out</button> : <button onClick={() => navigate('/login') }>Sign In</button>} </li>
Here is the code for Navbar.tsx so far.
import { Link } from "react-router-dom"; import { getAuth,signOut } from "firebase/auth"; import { useNavigate } from "react-router-dom"; export default function NavBar() { const isLoggedIn = true; const email = "grace@gmail.com"; const navigate = useNavigate(); return ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/articleslist">Articles</Link> </li> {isLoggedIn && ( <li style={{ color: 'white'}}> Logged in as {email} </li> )} <li> {isLoggedIn ? <button onClick={() => signOut(getAuth())}>Sign Out</button> : <button onClick={() => navigate('/login') }>Sign In</button>} </li> </ul> </nav> ); }
- Now testing if we set
const isLoggedIn = falseand commented out the default const emailconstemail="grace@gmail.com";, we will see the default sign in button.
Create a Custom React Hook
Summary:
- Replaced hardcoded login logic in React Navbar.tsx
- Created a reusable
useUser()hook to manage user state
Before, my React components checked login status directly using hardcode configuration like:
const isLoggedIn = true; const email = "grace@gmail.com";
We need to add logic configuration for the following:
- Detect if a user is logged in or not
- Wait until Firebase finishes verifying auth
- Get user info like
email,uid, etc.
Steps:
Create a new file inside the
srcdirectory called/src/useUser.jsimport { useState, useEffect } from 'react'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; const useUser = () => { const [isLoading, setIsLoading] = useState(true); //track loading state of Firebase const [user, setUser] = useState(null); // track user data that we are getting from Firebase auth // Firebase auth state change listener (changes in auth state) useEffect(() => { // callback function when auth state changes (user logs in or out) or firebase auth loads the current user authentication state // need const unsubscribe to avoid memory leaks const unsubscribe = onAuthStateChanged(getAuth(), function (user) { setUser(user); // set user data setIsLoading(false); // set loading state to false }); return unsubscribe; // unsubscribe from the listener when the component unmounts }, []); //add arrow dependency to run only once when the component mounts return { user, isLoading }; // return user data and loading state } export default useUser; // export the hook- Use
useUser()in/src/Navbar.tsxUse
useUser()in any component to get the current Firebase user and loading state so that if the user didnt sign in yet, the signin in Navbar appear and display the current user that is logged in. On the other hand, if the user is not yet logged in, the signout button will appear in the navbar. Here is the modified configuration of Navbar.tsximport { Link } from "react-router-dom"; import { getAuth, signOut } from "firebase/auth"; import { useNavigate } from "react-router-dom"; import useUser from "./useUser"; //the hook was imported export default function NavBar() { const { isLoading, user } = useUser(); //check if user is logged in. The useUser() gives the status and save the details to const const navigate = useNavigate(); return ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/articleslist">Articles</Link> </li> {isLoading ? <li>Loading...</li> : ( <> {user && ( <li style={{ color: 'white' }}> Logged in as {user.email} </li> )} <li> {user ? <button onClick={() => signOut(getAuth())}>Sign Out</button> : <button onClick={() => navigate('/login')}>Sign In</button>} </li> </> )} </ul> </nav> ) }
Adding Firebase Auth to Nodejs
In this activity we will
- Integrated Firebase Admin SDK on the backend using Node.js middleware
- Add Firebase Auth to Node.js Backend (Express + Firebase Admin)
Install firebase-admin npm module to add authentication to our back-end code.
npm install firebase-admin
Generate Service Account Credentials
- Go to Firebase Console → Project Settings → Service Accounts
- Click “Generate New Private Key”
- Save it as
credentials.jsonin yourback-end/directory - Add the credentials to
.gitignoreto prevent pushing secrets:


I added firebase-admin integratiion configuration in
server.ts. This code was from image in Step 3.import admin from 'firebase-admin'; import fs from 'fs'; const serviceAccount = JSON.parse( fs.readFileSync('./credentials.json') ); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), });
Protecting Endpoints Using Auth Tokens
After successfully configuring Firebase Authentication in the frontend using a custom useUser hook and integrating firebase-admin in the backend, the next step is securing our Node.js API endpoints.
Previously:
- I created custom
useUserReact hook to check login state - Integrated Firebase Admin SDK in our Node.js backend (
server.ts) - Used
credentials.jsonto authenticate our server - Added sign-in/sign-out logic in the
NavBar.tsx
Now we want to ensure that only logged-in users can POST data, such as adding comments or upvoting articles. We’ll do this by:
- Sending the user's Firebase Auth token from the frontend
- Verifying it on the backend
- Making the token’s
uid(user ID) available in backend routes
Step 1
Added the middleware configuration to determine the current state of the user
// Middleware to check every request if the user is authenticated. The next is a callback function that is called when the middleware is done. It is used to pass control to the next middleware function in the stack. app.use(async function(req, res, next) { // authtoken is the name of the header that we are sending from the front-end to the back-end. It is used to identify the user. // assigning the authtoken to the constant variable authtoken const { authtoken } = req.headers; // use firebase-admin to verify the token. If the token is valid, it will return the user object. If the token is invalid, it will throw an error. if (authtoken) { // verifyIdToken is a method that verifies the token and returns the user object. The user object contains the uid, email, and other information about the user. // The authtoken is passed to the verifyIdToken method to verify the token. const user = await admin.auth().verifyIdToken(authtoken); // The user object is assigned to the req.user variable. This variable can be used in the next middleware function to identify the user. Sample are the post endpoints below. req.user = user; } else { res.sendStatus(400); } // Done with the middleware function. The next() function is called to pass control to the next middleware function in the stack. next(); });
| Step | What Happens |
|---|---|
| 1 | The frontend sends a Firebase token in Authorization or custom header like authtoken |
| 2 | Middleware extracts the token from req.headers |
| 3 | firebase-admin verifies the token and retrieves the user |
| 4 | Middleware stores the user in req.user |
| 5 | The next route (like app.post) can access the user's uid |
Protecting the Upvote and Comment Endpoints
Previously, I configired middleware
app.use(async function(req, res, next) {
const { authtoken } = req.headers;
if (authtoken) {
const user = await admin.auth().verifyIdToken(authtoken);
req.user = user;
} else {
res.sendStatus(400);
}
next();
});This gives us access to the user’s uid, email, and other Firebase-authenticated properties in any endpoint through the which was stored in req.user
We will use these information to add other rules:
- Allow upvoting only if the user hasn’t already upvoted
- Keep track of user IDs that already upvoted
To protect Upvote, here are the steps
Configure the following
app.post('/api/articles/:articleName/upvote', async (req, res) => { const { articleName } = req.params; // The req.user has the uid of the user who is logged in which is then stored in the const uid variable. const { uid } = req.user; const article = await db.collection('articles').findOne({ articleName}); // const upvoteIds is an array that contains the ids of the users who have upvoted the article. The upvoteIds is used to check if the user has already upvoted the article. If the user has already upvoted the article, the user will not be able to upvote the article again. // the || [] is used to assign an empty array to the upvoteIds variable if the upvoteIds is undefined. This is done to avoid errors when checking if the user has already upvoted the article. const upvoteIds = article.upvoteIds || []; // The canUpvote is a boolean variable that checks if the user can upvote the article. If the user is logged in and has not already upvoted the article, the user can upvote the article. const canUpvote = uid && !upvoteIds.includes(uid); if (canUpvote) { const updatedArticle = await db.collection('articles').findOneAndUpdate({articleName }, { $inc: { upvotes: 1 }, //push is used to add the uid of the user who has upvoted the article to the upvoteIds array. This is done to keep track of the users who have upvoted the article. The $push operator is used to add the uid to the upvoteIds array. $push: { upvoteIds: uid }, }, { returnDocument: 'after', }); res.json(updatedArticle); } else { res.sendStatus(403); } });
Next we need to make sure that the front-end includes authtoken when making request. The topic below will discuss how to make requests with auth tokens.
Making Requests with Auth Tokens
We've already:
- Integrated
firebase-adminin our backend to verify users - Built a custom
useUserhook to get the current user in React
Now, we'll send Firebase Auth Tokens from frontend to backend, and protect the upvote and comment endpoints.
In your
ArticlePage.tsxcomponent, we import ouruseUserhook:import useUser from '../useUser';Get the current user and loading state:
const { isLoading, user } = useUser();Add token to the
onUpvoteClickedfunction:const token = user && await user.getIdToken(); const headers = token ? { authtoken: token } : {}; await axios.post(`/api/articles/${name}/upvote`, null, { headers });Add token to comment request:
const token = user && await user.getIdToken(); const headers = token ? { authtoken: token } : {}; await axios.post(`/api/articles/${name}/comments`, { postedBy: nameText, text: commentText, }, { headers });
- Now in our UI, we need to tweak something...to hide Upvote & Comment if Not Logged In
Inside your
ArticlePage.tsx, conditionally render:{user && <button onClick={onUpvoteClicked}>Upvote</button>} {user ? ( <AddCommentForm onAddComment={onAddComment} /> ) : ( <p>Log in to add a comment</p> )}
- Summary:
- Backend checks for valid authtoken before allowing access
- Frontend sends authtoken with each POST request
- UI hides buttons unless user is authenticated
As a result, when I click Upvote twice as user raymund, the console log of chrome cbrowser throws an error as we set in the script that each user can only vote once

Preparing an App for Release
To prepare my full-stack app for deployment, I needed to configure the backend to serve the frontend build files. First, I ran the production build command from the
front-enddirectory:Run
npm run buildin the front-end directoryMac:front-end marygracezabala$ npm run build > front-end@0.0.0 build > tsc -b && vite build vite v6.2.6 building for production... ✓ 118 modules transformed. dist/index.html 0.46 kB │ gzip: 0.30 kB dist/assets/index-DDG7WKTu.css 1.32 kB │ gzip: 0.64 kB dist/assets/index-JI3FNf4K.js 475.45 kB │ gzip: 135.64 kB ✓ built in 796ms Mac:front-end marygracezabala$
The Typescript Challenge
As part of my learning journey, I chose to build the React frontend using TypeScript with Vite. However, the LinkedIn Learning course I'm following — React: Creating and Hosting a Full-Stack Site — uses JavaScript instead. Because of this mismatch, I initially encountered build errors during
npm run buildsince TypeScript expected strict type definitions that were missing or mismatched from the course code.Even though I had ESLint set up to help detect code issues, the TypeScript compiler failed the build due to type inconsistencies.
The Fix
To address this, I created a new Git branch: Ch6_PrepareAppForRelease. In this branch, I revised several parts of the code to fully support TypeScript.
The
npm run buildcompiles the code, outputs optimized build files, and ensures the app is ready for deployment. It also improves code readability for other developers and teams who may review or contribute to the project.As you see in the code above in Step 1, the
npm run buildcreates a single dist directory folder inside front-and and consists of three files:dist/index.html 0.46 kB │ gzip: 0.30 kB dist/assets/index-DDG7WKTu.css 1.32 kB │ gzip: 0.64 kB dist/assets/index-JI3FNf4K.js 475.45 kB │ gzip: 135.64 kBMove the dist directory created in the fron-end to backend under public folder

In .gitignore, I also added the .gitignore **/dist

To ensure that any request not targeting our API (i.e., not starting with
/api) is handled by the frontend, we need to serve our frontend build files from the backend. We can achieve this by adding the following lines to ourserver.tsfile in the/srcdirectory:// Serve static files from the frontend's build directory app.use(express.static(path.join(__dirname, '../public/dist'))); // For any route that doesn't start with /api, send back index.html app.get(/^(?!\/api).+/), (req: Request, res: Response) => { res.sendFile(path.join(__dirname, '../public/dist', 'index.html')); };This setup allows React to handle routing on the client side, while keeping API routes separate on the backend.
Now, once we run our backend, it can alreay server the front end files

Next, we’ll make our backend more flexible by allowing it to run on any port defined by the environment — rather than hardcoding port
8000.To do this, update the
server.tsfile and replace the fixed port number with an environment variable fallback:// Use environment variable PORT if available, otherwise default to 8000 const PORT = process.env.PORT || 8000; async function start(): Promise<void> { await connectToDB(); app.listen(PORT, () => { console.log(`Express is listening at http://localhost:${PORT}`); }); } start();This change allows the app to adapt when deployed to platforms like Heroku, AWS, or Vercel, which assign ports dynamically via environment variables.
You can setup .env variable in the directory and add that in .gitignore if you want to hide the port in the script
Setting up Hosting for MongoDB
As of now, I only set the mongodb in my local macbook, in order to release it in the internet, we ned to setup hosting for it.
Use a hosted solution for mongodb. For now, I will use the free hosted mongodb called Atlas, provided by MongoDB itself.
First, create and account on MongoDb Atlas (https://cloud.mongodb.com).

Choose Username and password and the click Create Database User.

Then add .env file in the backend directory. Dont forget to add the .env in .gitignore so you does not accidentally commit the username and password

After that, you need to choose a connection method Shell

- Then after that, choose an operating system. Then it will give you an instruction on how to connect to it. I selected Ubuntu because I plan to deploy the application on an AWS EC2 instance running Ubuntu later on. I will test it in on my local Mac first.


Then, copy the connection string
For Ubuntu and MacOS users
mongosh "mongodb+srv://cluster0.hgcgwa0.mongodb.net/" --apiVersion 1 --username <username> --password <password>When I test the connection, it succesfully connected
marygracezabala@Mac React Full Stack % mongosh "mongodb+srv://cluster0.hgcgwa0.mongodb.net/" --apiVersion 1 --username <username> --password <password> Current Mongosh Log ID: 680afcd2874449549e57d86b Connecting to: mongodb+srv://<credentials>@cluster0.hgcgwa0.mongodb.net/?appName=mongosh+2.5.0 Using MongoDB: 8.0.8 (API Version 1) Using Mongosh: 2.5.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ Atlas atlas-ahmvpr-shard-0 [primary] test>Later on if you want to chenge OS, you can click the button "get Connection string"

If you are using codespaces or google app, you can add firewall acl rules to connect to mongodb
You can add your specific IP, but for this blog, I will sample add 0.0.0.0/0(anyip address)

- Next I will recreate our mongodb with the same name as our locally created db.

Setting up Environment Variables for MongoDB
Reconfigure the mongodb uri in
src/server.tsasync function connectToDB(): Promise<void> { const uri = process.env.MONGODB_USERNAME ? `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.DATABASE_NAME}/?retryWrites=true&w=majority&appName=Cluster0` : 'mongodb://127.0.0.1:27017';In order to know the url you need to go to Databse -> Connect -> Drivers

Then it will show you the connection string like this:
mongodb+srv://full-stack-react-server:<db_password>@cluster0.hgcgwa0.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0In the code above I changed the url to include the environment variables like this:
mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.DATABASE_NAME}/?retryWrites=true&w=majority&appName=Cluster0In .env, file, I configured it like this for example
.env
MONGODB_USERNAME=johndoereact MONGODB_PASSWORD=v3rys3cur3 DATABASE_NAME=cluster0.xxxxx.mongodb.netGot to
package.jsonin the backend and add a start scriptpackage.json
//delete this autorestart as this is just for development "start": "tsc && node dist/server.js", //replace with this code as this is more suitable for production "start": "node src/server.ts",Inside the back-end directory create a new file
app.yaml. This tells the google cloud what environment it will run on.app.yaml
includes: - prod-env.yaml runtime: nodejs22.xI also added new file called
prod-env.yamlthat contains all of our environment variableprod-env.yaml
MONGODB_USERNAME=johndoereact MONGODB_PASSWORD=v3rys3cur3 DATABASE_NAME=cluster0.xxxxx.mongodb.netAdd the prod-env.yaml to .gitignore
**/node_modules/ **/dist/ **/dist-ssr/ **/*.local **/prod-env.yaml
Setting it up in AWS
Create a Dockerfile in
/back-enddirectoryDockerfile
# Use official Node.js base image FROM node:22-slim # Set working directory WORKDIR /app # Copy package.json and install dependencies COPY package*.json ./ RUN npm install # Copy source code COPY . . # Build TypeScript to JavaScript RUN npm run build # Expose the port (match the PORT you use in app) EXPOSE 8000 # Start the app CMD ["node", "dist/server.js"]Add the following in the .dockerignore under backend directory
.dockerignore
# Node dependencies node_modules/ # Build output (Building inside Docker) dist/ # Local env files .env .env.local # System files .DS_Store # Git repo .git/ .gitignore # Frontend build front-end/I have a problem building the image because it said that mongodb was not installed.
Install mongodb locally in Macbook
marygracezabala@aklatcyber back-end % npm install mongodb added 15 packages, changed 1 package, and audited 358 packages in 6s 63 packages are looking for funding run `npm fund` for details found 0 vulnerabilitiesAfter you installed mongodb, you will notice that package.json was modified as it will add the mongodb.
Then build the docker image
marygracezabala@aklatcyber back-end % docker build --no-cache -t my-backend-app . [+] Building 54.1s (18/18) FINISHED docker:desktop-linux => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 989B 0.0s => [internal] load metadata for docker.io/library/node:22.14-slim 0.6s => [auth] library/node:pull token for registry-1.docker.io 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 71B 0.0s => [internal] load build context 0.0s => => transferring context: 1.57kB 0.0s => [builder 1/8] FROM docker.io/library/node:22.14-slim@sha256:1c18d9ab3af4585870b92e4dbc5cac5a0dc77dd13df1a5905cea89fc720eb05b 0.0s => => resolve docker.io/library/node:22.14-slim@sha256:1c18d9ab3af4585870b92e4dbc5cac5a0dc77dd13df1a5905cea89fc720eb05b 0.0s => CACHED [builder 2/8] WORKDIR /app 0.0s => [builder 3/8] COPY package.json tsconfig.json ./ 0.0s => [builder 4/8] RUN npm install 20.3s => [builder 5/8] COPY src ./src 0.1s => [builder 6/8] COPY public ./public 0.0s => [builder 7/8] RUN npm install --save-dev @types/mongodb 1.1s => [builder 8/8] RUN npm run build 0.9s => [stage-1 3/6] COPY --from=builder /app/package.json . 0.0s => [stage-1 4/6] COPY --from=builder /app/public ./public 0.0s => [stage-1 5/6] COPY --from=builder /app/dist ./dist 0.0s => [stage-1 6/6] RUN npm install --omit=dev 26.0s => exporting to image 4.9s => => exporting layers 3.8s => => exporting manifest sha256:296cb4633e6176a6cea6eb454a1d5c7a6f54111301d516f61e033b1d0db13800 0.0s => => exporting config sha256:56d32326541dffe15053ee4b210fa7ad4ecd688e34a82da11e07ee0c22d058f2 0.0s => => exporting attestation manifest sha256:174a18a77beed8bd4bf7a08a0ec05e763dba7b2b5e9b554530b8b7c2a7e7c61b 0.0s => => exporting manifest list sha256:45c8950cfdcc217fecdd30ae262d4283e47718ab89b6db7757a9623c9511a0b6 0.0s => => naming to docker.io/library/my-backend-app:latest 0.0s => => unpacking to docker.io/library/my-backend-app:latest 1.1s marygracezabala@aklatcyber back-end %You will then notice that the docker image was created below

Create Key in AWS Sercret Manager

Change the server.ts configuration to read the credentials.json of firebase from credentials.json to environment variables
// environment variable for Firebase credentials const serviceAccountJson = process.env.FIREBASE_CREDENTIALS_JSON; if (!serviceAccountJson) { throw new Error('Missing FIREBASE_CREDENTIALS_JSON environment variable'); } const serviceAccount = JSON.parse(serviceAccountJson); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), });async function connectToDB(): Promise<void> { const uri = process.env.MONGODB_USERNAME ? `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.DATABASE_NAME}/?retryWrites=true&w=majority&appName=Cluster0` : 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, }, });Create new github actions flow
name: Deploy to AWS on: push: branches: [ main ] jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout repo uses: actions/checkout@v4 - name: Login to Amazon ECR uses: aws-actions/amazon-ecr-login@v2 - name: Build Docker image run: | docker build -t ${{ secrets.ECR_REPOSITORY }}:latest ./back-end docker tag ${{ secrets.ECR_REPOSITORY }}:latest ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${{ secrets.AWS_REGION }}.amazonaws.com/${{ secrets.ECR_REPOSITORY }}:latest - name: Push Docker image run: | docker push ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${{ secrets.AWS_REGION }}.amazonaws.com/${{ secrets.ECR_REPOSITORY }}:latest- As you see, in your github actions, you used secret variables. You need to define this in github as well. Here are the steps toset up the sercrets
- Go to the github repository for example under my repository -> https://github.com/grace188031/react-blog
- Click Settings ➔ Secrets and variables ➔ Actions ➔ New repository secret
- Then, one by one, enter the secrets
Secret Name Value AWS_ACCESS_KEY_IDYour AWS access key (for programmatic access) AWS_SECRET_ACCESS_KEYYour AWS secret access key AWS_REGIONExample: us-east-1ECR_REPOSITORYExample: your-ecr-repo-name(likereact-fullstack-app)AWS_ACCOUNT_IDYour 12-digit AWS account ID 
Create a runner in github
# Stage 1: Build Stage FROM node:22.14-slim AS builder # Set working directory WORKDIR /app # Copy package.json and package-lock.json if exists COPY package.json tsconfig.json ./ # Install dependencies RUN npm install # Copy source code COPY src ./src COPY public ./public #INSTALL MongoDB RUN npm install --save-dev @types/mongodb # Build the TypeScript code (compiles src/*.ts into dist/*.js) RUN npm run build # Stage 2: Production Stage FROM node:22.14-slim WORKDIR /app # Copy only the necessary files from the builder stage COPY --from=builder /app/package.json . COPY --from=builder /app/public ./public COPY --from=builder /app/dist ./dist # Install only production dependencies (no devDependencies) RUN npm install --omit=dev # Expose port (optional: you can specify which port your app listens to) EXPOSE 8000 # Run the server (compiled JS from dist/server.js) CMD ["node", "dist/server.js"]Run and deploy the runner.

- You will then notice that there is a container image deployed in your amazon ECR repository

Next blog: I will deploy kubernetes, update the github actions workflow, and add ingress nginx loadbalancer with k8s.

No Comments