fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← React

React / 6 MIN READ

Serverless Functions

Implementing serverless functions

From the original Fervor library. Examples may use older package versions.

I will present a comprehensive tutorial in three sections to help you create a Vite React app that utilizes serverless functions on Netlify and connects to a PlanetScale MySQL database. Here is part one:

Part 1: Setting Up Your Development Environment and Initializing the Project

1. Pre-requisites

Before you start, ensure that you have the following installed on your system:

  1. Node.js and npm: Download and install the latest version from the official website.
  2. A GitHub account: You will use this to store your project repository.
  3. A Netlify account: This is required for deploying your app.
  4. A PlanetScale account: You will use this to set up your MySQL database.

Verify your Node.js and npm installation by running the following commands in your terminal:

node -v
npm -v

2. Creating a New Vite Project

Initialize a new Vite React project using the following command:

npm init vite@latest my-vite-app --template react

This will create a new project directory called my-vite-app with a basic React setup. Navigate to your project directory:

cd my-vite-app

3. Exploring the Project Structure

Your initial project structure will look something like this:

  • src/: This is where your source files reside. The main.js file is the entry point for your app.
  • public/: This directory holds static assets that are not imported from your source files.
  • package.json: This file contains metadata about your project, such as dependencies and scripts.
  • vite.config.js: This file (which you might need to create) allows you to configure the behavior of Vite.

4. Initializing a Git Repository

Initialize a Git repository in your project directory:

git init

Connect your local repository to a new GitHub repository (replace your-github-repo-url with the URL of your new GitHub repository):

git remote add origin your-github-repo-url

Commit your initial project files:

git add .
git commit -m "Initial commit"

Push your commits to GitHub:

git push -u origin main

This concludes part one of the tutorial. Here, we set up the development environment and initialized a new Vite React project. In the next part, we will cover setting up serverless functions with Netlify and connecting to a PlanetScale MySQL database.

Moving forward with the next part.

Part 2: Setting Up Serverless Functions on Netlify and Creating a PlanetScale Database

1. Setting Up Serverless Functions on Netlify

1.1. Installing Netlify CLI

Install the Netlify CLI globally using npm. This tool will help you manage and deploy your Netlify site from the command line:

npm install -g netlify-cli

1.2. Initializing Netlify in Your Project

Inside your project directory, initialize a new Netlify site:

netlify init

Follow the prompts to create a new site or link to an existing site on your Netlify account.

1.3. Setting Up Netlify Functions

Create a directory for your serverless functions, as specified in your netlify.toml file. By default, this would be netlify/functions. Create a new file for your function handler, e.g., handler.js:

mkdir -p netlify/functions
touch netlify/functions/handler.js

Write a basic serverless function in handler.js:

exports.handler = async function(event, context) {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Hello World" }),
  };
};

2. Creating and Configuring a PlanetScale Database

2.1. Sign Up and Create a New Database

Sign up for a PlanetScale account and log in to the PlanetScale dashboard. Create a new database and a new branch (main branch by default).

2.2. Creating a Schema

Using the PlanetScale web console, create a schema for a simple users table:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255),
  email VARCHAR(255),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. Connecting the Serverless Function to PlanetScale Database

Configure your Netlify function (handler.js) to connect to the PlanetScale database:

3.1. Installing MySQL2 Library

Install the mysql2 npm package in your project directory to allow Node.js to interact with MySQL:

npm install mysql2

3.2. Setting Up Connection to PlanetScale

Modify handler.js to set up a connection to your PlanetScale database using the MySQL2 library:

const mysql = require('mysql2/promise');

const connectionConfig = {
  host: 'your-planetscale-host',
  user: 'your-planetscale-username',
  password: 'your-planetscale-password',
  database: 'your-planetscale-database',
};

let connection;

exports.handler = async (event, context) => {
  try {
    if (!connection || connection.state === 'disconnected') {
      connection = await mysql.createConnection(connectionConfig);
    }

    const [rows] = await connection.execute('SELECT * FROM users');
    
    return {
      statusCode: 200,
      body: JSON.stringify(rows),
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: error.message }),
    };
  }
};

In part 3, we will integrate a React component that communicates with the serverless function, which in turn interacts with the PlanetScale database. I will guide you through creating the React component, testing the application locally, and deploying it to Netlify. Here we go:

Part 3: Creating a React Component and Deploying the Application

1. Creating a React Component to Interact with the Database

1.1 Creating a Database Viewer Component

In your src directory, create a new component named DatabaseViewer.js. This component will fetch data from your serverless function and display it.

// src/DatabaseViewer.js
import React, { useState, useEffect } from 'react';

function DatabaseViewer() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('/.netlify/functions/handler');
        const result = await response.json();
        setData(result);
      } catch (error) {
        setError(error);
      }
    };

    fetchData();
  }, []);

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Database Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default DatabaseViewer;

1.2 Integrating the Database Viewer Component into Your App

Integrate the DatabaseViewer component into your main component (src/App.jsx or src/App.js):

import React from 'react';
import DatabaseViewer from './DatabaseViewer';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <DatabaseViewer />
      </header>
    </div>
  );
}

export default App;

2. Testing Your App Locally

Test your app locally using Vite’s development server. Run the following command in your project directory:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see data fetched from the database displayed on the page.

3. Deploying Your App to Netlify

3.1 Committing Your Changes to GitHub

Once you are satisfied with your local testing, commit all your changes to your GitHub repository:

git add .
git commit -m "Integrated React app with serverless function and database"
git push

3.2 Deploying to Netlify

Deploy your app to Netlify using the Netlify CLI:

netlify deploy --prod

Follow the prompts to deploy your site. Once deployed, you will receive a link to your live site.

And that concludes our tutorial!

Keep your curiosity going.Explore more React →
287 TUTORIALS · 22 TOPICSREADY