building-a-full-stack-application-with-react-and-nestjs.html

Building a Full-Stack Application with React and NestJS

In the ever-evolving landscape of web development, building a full-stack application can be a rewarding yet challenging task. If you're looking to create a dynamic and robust application, combining React for the front end and NestJS for the back end can lead to powerful results. In this article, we’ll explore how to build a full-stack application using these technologies, providing you with actionable insights, coding examples, and step-by-step instructions to get started.

What is a Full-Stack Application?

A full-stack application consists of both the front end (the client side) and the back end (the server side). The front end is what users interact with directly, while the back end manages data, business logic, and server-side operations. By using a combination of React and NestJS, you can leverage the strengths of both frameworks to create a seamless user experience.

Why Choose React and NestJS?

  • React: A powerful JavaScript library for building user interfaces. It allows for the creation of reusable components, making it easier to manage complex UIs.
  • NestJS: A progressive Node.js framework that uses TypeScript. It’s designed for building efficient, reliable, and scalable server-side applications. NestJS follows the modular architecture, making it easier to maintain and test.

Setting Up Your Development Environment

Before diving into coding, let’s set up our development environment.

Prerequisites

  • Node.js (v12 or later)
  • npm or Yarn
  • A code editor (like VSCode)

Installation Steps

  1. Install React App: Open your terminal and create a new React application using Create React App: bash npx create-react-app my-fullstack-app cd my-fullstack-app

  2. Set Up NestJS: In a new terminal window, install the NestJS CLI globally: bash npm install -g @nestjs/cli Create a new NestJS project: bash nest new backend cd backend

Structuring Your Application

Directory Structure

Your project directory should look like this:

my-fullstack-app/
├── backend/             # NestJS backend
│   ├── src/
│   ├── package.json
├── frontend/            # React frontend
│   ├── src/
│   ├── package.json

Building the Backend with NestJS

Creating a Simple REST API

  1. Generate a Module, Controller, and Service: Navigate to the backend directory and run: bash nest g resource items This command will create a new module, controller, and service for managing items.

  2. Implementing the Service: Open src/items/items.service.ts and modify it to handle a simple in-memory array: ```typescript import { Injectable } from '@nestjs/common'; import { Item } from './item.interface';

@Injectable() export class ItemsService { private readonly items: Item[] = [];

 create(item: Item) {
   this.items.push(item);
 }

 findAll(): Item[] {
   return this.items;
 }

} ```

  1. Setting Up the Controller: In src/items/items.controller.ts, implement the routes: ```typescript import { Controller, Get, Post, Body } from '@nestjs/common'; import { ItemsService } from './items.service'; import { Item } from './item.interface';

@Controller('items') export class ItemsController { constructor(private readonly itemsService: ItemsService) {}

 @Post()
 create(@Body() item: Item) {
   this.itemsService.create(item);
 }

 @Get()
 findAll() {
   return this.itemsService.findAll();
 }

} ```

  1. Define the Item Interface: Create a new file src/items/item.interface.ts: typescript export interface Item { id: number; name: string; }

  2. Run the NestJS Server: Start your NestJS application: bash npm run start

Building the Frontend with React

Connecting to the NestJS Backend

  1. Install Axios: In your frontend directory, install Axios for making HTTP requests: bash npm install axios

  2. Creating an Item Component: In src/components/ItemForm.js, create a form to add items: ```javascript import React, { useState } from 'react'; import axios from 'axios';

const ItemForm = () => { const [name, setName] = useState('');

 const handleSubmit = async (e) => {
   e.preventDefault();
   await axios.post('http://localhost:3000/items', { id: Date.now(), name });
   setName('');
 };

 return (
   <form onSubmit={handleSubmit}>
     <input 
       type="text" 
       value={name} 
       onChange={(e) => setName(e.target.value)} 
       required 
     />
     <button type="submit">Add Item</button>
   </form>
 );

};

export default ItemForm; ```

  1. Displaying Items: Create a component to display the list of items: ```javascript import React, { useEffect, useState } from 'react'; import axios from 'axios';

const ItemList = () => { const [items, setItems] = useState([]);

 useEffect(() => {
   const fetchItems = async () => {
     const res = await axios.get('http://localhost:3000/items');
     setItems(res.data);
   };
   fetchItems();
 }, []);

 return (
   <ul>
     {items.map(item => (
       <li key={item.id}>{item.name}</li>
     ))}
   </ul>
 );

};

export default ItemList; ```

  1. Integrate Components: In src/App.js, integrate the form and the list: ```javascript import React from 'react'; import ItemForm from './components/ItemForm'; import ItemList from './components/ItemList';

const App = () => { return (

Item Manager

); };

export default App; ```

Running Your Full-Stack Application

  1. Start the React App: In the frontend directory, run: bash npm start

  2. Access Your Application: Open your browser and navigate to http://localhost:3000. You should see your Item Manager, where you can add and view items.

Conclusion

Building a full-stack application with React and NestJS can be straightforward when you break it down into manageable steps. By following this guide, you’ve created a simple application that demonstrates the power of these frameworks. You can expand upon this base by adding features such as user authentication, database integration, and more.

As you continue to develop your skills, remember to explore the extensive documentation for both React and NestJS, and don't hesitate to dive into community resources for troubleshooting and optimization techniques. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.