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.