Skip to main content

One post tagged with "Full-Stack"

View All Tags

Building a Full-Stack Application with Wasp Integrating Server and Front-End Components

· 4 min read
Pourya Bagheri
Quantum Computing | Blockchain Soloution | MERN

Wasp is a modern, declarative language that enables developers to rapidly build full-stack web applications. By abstracting the complexities of setting up both the server and the client, Wasp lets you focus on your application’s logic and design. In this article, we’ll walk through creating a simple full-stack app that includes a server API endpoint and a front-end that fetches and displays data from that endpoint.

Application Overview

Our example application, MyFullStackApp, demonstrates how to:

  • Define the overall app configuration.
  • Set up a routing structure for navigation.
  • Build a React-based front-end component.
  • Create a server endpoint that responds with a greeting message.

The complete code example is shown below.

Code Example


app MyFullStackApp {
title: "My Full-Stack Wasp App"
description: "A full-stack application example built with Wasp that integrates server and front-end components."
}

route HomeRoute {
path: "/"
component: HomePage
}

page HomePage {
component: HomePageComponent
}

component HomePageComponent {
<div>
<h1>Welcome to My Full-Stack Wasp App!</h1>
<p>This example demonstrates how to connect your front-end with a server API.</p>
<GreetingComponent/>
</div>
}

component GreetingComponent {
<script>
import React, { useEffect, useState } from 'react';

function GreetingComponent() {
const [greeting, setGreeting] = useState("");

useEffect(() => {
fetch("/api/greeting")
.then(response => response.json())
.then(data => setGreeting(data.greeting))
.catch(error => console.error("Error fetching greeting:", error));
}, []);

return (
<div>
<p>{greeting ? greeting : "Loading greeting..."}</p>
</div>
);
}

export default GreetingComponent;
</script>
}

server getGreeting {
handler: function(req, res) {
// Respond with a greeting message in JSON format
res.json({ greeting: "Hello from the server!" });
},
method: "GET",
path: "/api/greeting"
}

Detailed Explanation

1. Application Setup

  • App Definition:

    The app block defines the general configuration for the application, such as its title and description. This acts as a central declaration point for your project.

  • Routing:

    The route HomeRoute block maps the root path ("/") to the HomePage page. This structure makes it easy to manage navigation within the app.

2. Front-End Components

  • Page and Component Structure:

    The HomePage page is linked to the HomePageComponent, which composes the visible UI elements. Within this component, a header and a brief description are provided, along with the inclusion of the GreetingComponent.

  • GreetingComponent:

    This is a React component embedded within a Wasp component. The component uses React’s hooks:

    • useState: Initializes the greeting state variable.
    • useEffect: Performs a fetch request to the server endpoint /api/greeting when the component mounts.

The fetched greeting is then displayed on the page. Error handling is also included to log any issues during the fetch operation.

3. Server-Side Code

  • Server Endpoint:

    The server getGreeting block defines an API endpoint:

    • handler: A function that sends a JSON response with a greeting message.

    • method: The HTTP method (GET) used to access this endpoint.

    • path: The URL path (/api/greeting) where the server listens for requests.

This server code demonstrates a typical pattern of exposing backend functionality via a RESTful API, which the front-end can consume.

4. Integration of Server and Front-End

  • Data Flow:

    When a user visits the homepage, the HomePageComponent renders and includes the GreetingComponent. On mounting, the GreetingComponent makes a GET request to the /api/greeting endpoint. The server responds with a JSON payload containing the greeting, which is then rendered in the UI. This seamless integration between server and client is one of Wasp’s strengths.

  • Declarative Structure:

    Wasp’s declarative syntax helps keep the code organized. Developers can easily see how the app is structured, which routes lead to which pages, and how components are interconnected with server actions.

How to Install, Run, and Deploy a Wasp Application

1. Prerequisites

Before you begin, make sure you have the following installed on your system:

  • Node.js and npm:

Verify the installation with these commands:

node -v
npm -v

2. Installing Wasp CLI

Method 1: Using curl

curl -L https://get.wasp-lang.dev | sh

Method 2: Using npm

npm install -g wasp-lang

3. Creating a New Project

Once the Wasp CLI is installed, you can create a new project by running:

Create a New Project:

wasp new my-fullstack-app

Navigate to the Project Directory:

cd my-fullstack-app

4. Running the Application in Development Mode

wasp start

5. Building the Production Version

When you are ready to deploy your app for end users, you need to create a production build:

wasp build

6. Deploying the Application

Deploying with Docker

FROM node:14
WORKDIR /app
COPY . .
RUN npm install
RUN wasp build
CMD ["npm", "start"]

Build the Docker Image:

docker build -t my-fullstack-app .

Run the Docker Container:

docker run -p 3000:3000 my-fullstack-app