Hello World with Serverless Functions
Tags: react, serverless, zeit, nextjs
Published: 2020-02-07 04:47:27

Technologies used in this post:

- React
- Next.js
- Node Serverless Functions
- Zeit

This post assumes a basic knowledge of React, Next.js, and Node. However, if you have no knowledge of Next.js, that is okay. If you know React, you can still follow along here. Just recognize that the file structure will be different, and there are *small* differences in the component files. That is another topic for another day, however 😁.

## All About Workflows

Zeit's platform is focused on building workflows for the everyday developer. They provide a production-ready, continuous development platform for anyone from brand new devs, to hobbyists, all the way to Enterprise companies like Hulu.

Starting a React project using Next.js and spinning up serverless node functions is incredibly simple. It truly is an amazing world we live in!

## Starting a Next.js Project

As Zeit is all about workflows, they have made it so simple to begin a new project. To follow the tutorial here, you'll need to set up a new account on their website, [zeit.co](https://zeit.co). 

### Step 1 - Choose a template

Once you are logged in, and in the dashboard, you will see a `New Project` button at the top right. Click that button, then scroll down to the "From a template" section. The Next.js template is the first on the list of templates here.

<img src="https://tk-assets.lambdaschool.com/06040209-a03e-43ba-8054-9164df41d5f8_ScreenShot2020-02-06at11.09.28AM.png" alt="List of templates" />

Click on that template to navigate to the configuration page. 

### Step 2 - Name your project

Here you will be able to name your project and also see a live example of the web app that is created with this template.

<img src="https://tk-assets.lambdaschool.com/f51c05b7-7af4-4043-9a4c-62c79cf98b69_ScreenShot2020-02-06at11.12.23AM.png" alt="tamplate overiew and creation page" />

After giving your new project a name, click `Continue` to move to the last step in the creation process. 

### Step 3 - Create a repo and deploy

The card in the UI now lets you create a Git repository, name the repository, and make it private if you wish. You will want to make a repo for this tutorial so you can clone the project onto your computer and work on it alongside me.

*Also note that you should keep the name of the repo the same as the Zeit project.*

Go ahead and hit `Deploy`!

### What is happening?

Behind the scenes here, Zeit will set up a modern React application powered by Next.js, add the repository to your GitHub account, and deploy the project on the Zeit platform. After clicking `Deploy` you will be navigated to your project's deployment page, where you can watch the progress of the build and deployment.

After the project is deployed, you'll be able to view the deployment overview by clicking the URL under the "Deployment" header. Also, if you click on the preview image, a new tab will be opened where you can view the web app itself.

<img src="https://tk-assets.lambdaschool.com/db868a07-6ba9-4a4c-9d3a-5815155a1a53_ScreenShot2020-02-06at11.37.03AM.png" alt="Deployment overview page" />

At this point, go to your repository and clone the project onto your machine. Then you'll be ready to add your first serverless function!

## Serverless Functions

According to Zeit's [docs](https://zeit.co/docs/v2/serverless-functions/introduction), serverless functions "are pieces of code written with backend languages that take an HTTP request and provide a response". Let's look at our project and find the serverless function that was built out already that the React app consumes to get a current timestamp. 

<img src="https://tk-assets.lambdaschool.com/2a9e8405-7b6a-4dac-a092-1148ba3365c1_ScreenShot2020-02-06at11.43.41AM.png" alt="image of web app with arrow pointing to timestamp and text saying this was fetched from a serverless function" />

In your project, you will see a `/pages` directory, and inside that, an `/api` directory. Go ahead and open `date.js` that is found in `/api`. Here is your first glimpse at a serverless function!

<img src="https://tk-assets.lambdaschool.com/a71273ec-cdd2-4c7f-a4a8-bb5f800fdd97_serverless.png" alt="serverless function code" />

This is just a node function that, as mentioned, takes an HTTP request and returns the current time. Let's take a look at how these functions work.

## Serverless Function Setup

As shown above, the serverless function in our Next.js app is simply an exported function that receives a `req` and a `res` object, just like node API endpoints. It is important to note that this actually isn't using Express to build these objects. Zeit has built these objects to mirror what Express does, but it is not Express.

When the HTTP request comes in, this function calls `res.json` to return the date stamp from the time the request came in. So Zeit allows our React app to make an async HTTP request to this function and will wait for the data to be returned. Let's see how that is set up on the client-side.

## React App Setup

Looking at the node function, at first glance it isn't intuitive how you would make a request to that function. What's the endpoint? How do you pass data to it? 

It's actually a really cool setup. The deployed (or even the development) instance knows that files in the `/api` directory are serverless functions. It builds the functions in the cloud, and then any request that goes out to `/api/[file-name]` is sent to that function.

So there is one single endpoint for each file, and one function for each endpoint. And we can make any HTTP requests to those functions by passing in the file name in the endpoint URL. 

Here is the fetch call that is happening in our Next.js app in the `/pages/index.js` file. Do you remember the name of the file that is housing the serverless function? Go ahead and look at it. That's right! It's `date.js`. So the React app makes a GET request to `/api/date`.

<img src="https://tk-assets.lambdaschool.com/b585e434-4363-49e2-bf7a-617198714ece_carbon.png" alt="React coding making a request to the serverless function" />

It's as simple as that! The call goes out asynchronously to the serverless function, awaits for the function to return the date, then sets the date to state so it can be displayed in the UI.

## Writing Your First Serverless Function

Now that you have seen this work, I want you to add this code to the JSX in your React app. Instead of the header saying "Welcome to Next!", I want it to greet you by name. So let's add some state and the extra piece in the JSX:
 

<img src="https://tk-assets.lambdaschool.com/b8cd0cfb-bb5f-4001-8805-d6b74ac3355c_add-state.png" alt="Code to add a state property called name and display that name in the UI" />

Once you have that added, follow these tasks:

- Add a new serverless file and function that will return your name (you can shape that data however you would like
- Build a new `useEffect` hook that will query that new function to get the name back
- Set the returned name to state so it will display in the header

Don't scroll down! Try this out on your own first before you see my implementation below 😁

<img src="https://media1.tenor.com/images/c8e4fcf06801572f496e02954df31612/tenor.gif?itemid=15057094" alt="Gif that says Don't cheat!" />

## My Code

How'd you do? Did you get it working? Here is how I implemented this. I added a file called `get-name.js` in the `/api` directory. The serverless function in that file looks like this:

<img src="https://tk-assets.lambdaschool.com/faa1ccc4-4f39-420f-85cd-0813489b5748_serverless-name.png" alt="serverless function that returns a name object with my name" /> 

Then I fetched the data like this:

<img src="https://tk-assets.lambdaschool.com/b1e30f7e-ff20-4807-8f4f-03deee829f79_name-effect.png" alt="code that shows an effect hook for calling the new serverless function" /> 

Is that about what you had? Share what you did differently in the comments!

## Conclusion

Now you know how to add serverless functions to a React app using Next.js and Zeit. The simplicity of the workflow makes this so easy. I love the developer experience and have found that I can build features so much faster with these amazing tools. Let me know what use cases you find for serverless functions, and how you're liking Zeit and Next.js!