How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?

Author: neptune | 31st-Jul-2024
#JavaScript #API

Creating a blogging website can be a rewarding project, especially when leveraging modern web development technologies like React, Node.js, and Jamstack architecture. In this article, I'll walk you through my journey of building a high-performance, scalable, and secure blogging site using these tools.


Build Your Website with React, Node.js & Jamstack

Understanding the Stack: React, Node.js, and Jamstack

React

React is a powerful JavaScript library for building user interfaces. Its component-based architecture and declarative syntax make it a popular choice for front-end development.

Node.js

Node.js is a JavaScript runtime that allows you to run JavaScript on the server side. It’s known for its performance and ability to handle asynchronous operations efficiently.


Jamstack

Jamstack stands for **JavaScript, APIs, and Markup**. It’s a modern web development architecture that decouples the frontend from the backend, offering benefits like improved performance, enhanced security, and better scalability.

Project Overview

The goal was to create a blogging website with the following features:

- A responsive design using React.

- A backend API built with Node.js.

- Static site generation and deployment leveraging the Jamstack architecture.


Step 1: Setting Up the Development Environment

1. Install Node.js and npm

First, I installed Node.js and npm, as they are essential for both React and Node.js development. You can download and install them from the [official Node.js website](https://nodejs.org/).

2. Set Up the React App

Using Create React App, I quickly set up a new React project:

    npx create-react-app my-blog

    cd my-blog



Step 2: Creating the Backend with Node.js

For the backend, I used Node.js along with Express, a popular web framework for building APIs.

1. Initialize the Backend

I created a new directory for the backend and initialized a new Node.js project:

    mkdir backend

    cd backend

    npm init -y



2. Install Dependencies

Next, I installed Express and other necessary dependencies:

    npm install express body-parser cors


3. Set Up the Server

I created an `index.js` file to set up the Express server:

    const express = require('express');

    const bodyParser = require('body-parser');

    const cors = require('cors');


    const app = express();

    app.use(bodyParser.json());

    app.use(cors());


    const posts = [

        { id: 1, title: 'First Post', content: 'This is my first post' },

        { id: 2, title: 'Second Post', content: 'This is my second post' },

    ];


    app.get('/api/posts', (req, res) => {

        res.json(posts);

    });


    app.listen(5000, () => {

        console.log('Server is running on port 5000');

    });



Step 3: Building the Frontend with React

With the backend set up, I focused on building the frontend using React.


1. Fetching Data from the API

In the React project, I created a service to fetch posts from the backend API:

    // src/services/postService.js

    export async function fetchPosts() {

        const response = await fetch('http://localhost:5000/api/posts');

        const data = await response.json();

        return data;

    }


2. Displaying Posts

I created a component to display the list of posts:

    // src/components/PostList.js

    import React, { useEffect, useState } from 'react';

    import { fetchPosts } from '../services/postService';


    export default function PostList() {

        const [posts, setPosts] = useState([]);


        useEffect(() => {

            async function getPosts() {

                const data = await fetchPosts();

                setPosts(data);

            }

            getPosts();

        }, []);


        return (

            <div>

                <h1>Blog Posts</h1>

                <ul>

                    {posts.map(post => (

                        <li key={post.id}>

                            <h2>{post.title}</h2>

                            <p>{post.content}</p>

                        </li>

                    ))}

                </ul>

            </div>

        );

    }



3. Integrating the Component

Finally, I integrated the `PostList` component into the main application:

    // src/App.js

    import React from 'react';

    import PostList from './components/PostList';


    function App() {

        return (

            <div className="App">

                <header className="App-header">

                    <h1>Welcome to My Blog</h1>

                </header>

                <main>

                    <PostList />

                </main>

            </div>

        );

    }


    export default App;



Step 4: Leveraging Jamstack for Static Site Generation

To leverage the benefits of Jamstack, I used a static site generator. For this project, I chose Next.js, a React framework with built-in support for static site generation.


1. Set Up Next.js

I created a new Next.js project and moved the components and services from the Create React App project:

    npx create-next-app my-next-blog

    cd my-next-blog


2. Create Static Pages

I modified the Next.js pages to fetch data at build time using `getStaticProps`:

    // pages/index.js

    import React from 'react';

    import { fetchPosts } from '../services/postService';


    export async function getStaticProps() {

        const posts = await fetchPosts();

        return {

            props: {

                posts,

            },

        };

    }


    const Home = ({ posts }) => (

        <div>

            <h1>Blog Posts</h1>

            <ul>

                {posts.map(post => (

                    <li key={post.id}>

                        <h2>{post.title}</h2>

                        <p>{post.content}</p>

                    </li>

                ))}

            </ul>

        </div>

    );


    export default Home;



Step 5: Deploying the Website

For deployment, I chose Vercel, a platform that supports Next.js and provides automatic builds and deployments.


1. Push to GitHub

I pushed the project to GitHub:

    git init

    git add .

    git commit -m "Initial commit"

    git remote add origin https://github.com/yourusername/my-next-blog.git

    git push -u origin main



2. Deploy to Vercel

I signed up for a free account on [Vercel](https://vercel.com/), linked my GitHub repository, and deployed the project. Vercel handled the build process and deployed the site, making it accessible via a custom domain.


Conclusion

Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience. This approach not only provided a smooth development workflow but also ensured that the website was fast, secure, and scalable. By leveraging static site generation and modern hosting solutions, I created a robust platform ready for future growth. Whether you’re a developer or a business owner, embracing Jamstack can significantly enhance your web development projects.




Related Blogs
Generate Fibonacci Sequence - JavaScript | Hackerank
Author: neptune | 07th-Apr-2023
#JavaScript #Hackerrank
Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Architecture of API Gateway
Author: neptune | 15th-Nov-2022
#API #Microservice
Creating an API starts with the publisher, where it will be designed, and it will be published to the store for the consumer to explore and subscribe...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

Why API Authentication?
Author: neptune | 01st-Jan-2023
#API
API's play a vital role in linking applications to exchange services and data. There are a variety of ways to authenticate API requests...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

View More