loading...
Cover image for Deploy a Daily Node.js backend server instantly
Daily

Deploy a Daily Node.js backend server instantly

philmillman profile image Phil Miller Originally published at daily.co ・5 min read

If you’ve been following our Daily DEV tutorials, you might’ve noticed Paul’s note in his post about building a video chat app with React:

“In real production code, you'll want to create rooms by calling the Daily REST API from your backend server, to avoid storing API keys in your client-side JavaScript.”

In the future, we’ll go into great detail about how to implement your server-side code, but for now we prefer to give you some building blocks to get you up-and-running as quickly as possible.

What we’ll build

We’re going to set up an instant Node.js server on Glitch. Glitch is a friendly, community-oriented developer tool that allows you to create projects from scratch or "remix" others for inspiration. Every project is backed by a real server, so you have everything you need to get started and to scale.

What you’ll need to build it

  • Daily account and API key: Sign up if you don’t have these yet.
  • Glitch account: If you plan on tweaking your server over time, we highly recommend signing up for Glitch. Though, you can still follow this tutorial without creating an account!

Get started

Click the Remix button below.

remix this

You should now have an editable copy of the server, which includes public API endpoints that return data via the Daily API. You’ll also have a handy web-based development environment.

Add your key

All you need to do to get going is to add your Daily API Key, which you can get from the dashboard in the Developers section.

Copy it to your clipboard and open the .env file in the Glitch editor. Paste it there (replacing Variable Value):

Screenshot of where to paste your Daily API key into the Glitch editor

At your service

Now let’s have a look at the server code (in server.js) and send a sample request.

First, open up the log view (Tools > Logs, located in the bottom left) and you should see:

💗🌴 Your app is listening on port 3000

This means the express server is running and listening for incoming requests [0].

Looking at the code you will see three sections.

In the first section we’re importing dependencies, clearing some useful constants, and setting up an axios instance to reference the Daily API.

const express = require("express");
const axios = require("axios");
const app = express();
app.use(express.json());

// MAKE SURE YOU HAVE ADDED YOUR API KEY IN THE .env file
const BASE_URL = "https://api.daily.co/v1/";
const API_AUTH = process.env.DAILY_API_KEY;

// create an axios instance that includes the BASE_URL and your auth token
// this may be useful to put in an external file to it can be referenced
// elsewhere once your application grows
const api = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
  headers: { Authorization: `Bearer ${API_AUTH}` }
Enter fullscreen mode Exit fullscreen mode

Next up are all the endpoints we’re creating on our server. Each of them is essentially a loose wrapper that calls its equivalent in the Daily API. Let’s look at the first one, as an example:

app.get("/rooms", async (request, response) => {
  try {
    const rooms = await apiHelper("get", "/rooms");
    response.json(rooms);
  } catch (e) {
    console.log("error: ", e);
    response.status(500).json({ error: e.message });
  }
});
Enter fullscreen mode Exit fullscreen mode

Here, we’re saying when a request comes in at /rooms we want to execute this async callback that makes a request to the Daily API using the apiHelper we defined below. If the request is successful then we send the response back to the requester as json. If it fails, then we send back an http 500 error with an accompanying error message.

Lastly, let’s look at the apiHelper function:

const apiHelper = async (method, endpoint, body = {}) => {
  try {
    const response = await api.request({
      url: endpoint,
      method: method,
      data: body
    });
    return response.data;
  } catch (error) {
    console.log("Status: ", error.response.status);
    console.log("Text: ", error.response.statusText);
    // need to throw again so error is caught
    // a possible improvement here is to pass the status code back so it can be returned to the user
    throw new Error(error);
  }
};
Enter fullscreen mode Exit fullscreen mode

The goal here is to have a reusable way to call the Daily API. It takes the following parameters:

  • method: the http request method
  • endpoint: the Daily API endpoint
  • body: the optional request body, required for POST, PUT, etc.

We’re using the request method from the axios instance we defined above, so we don’t have to worry about specifying the BASE_URL and Authorization header with every request. We’ve included some basic error handling here, but feel free to modify this as needed [1].

Sample request

You can verify all is working as intended by opening the Glitch preview (Click Show -> Next to The Code). Next click 'Change URL' and add [/rooms](https://docs.daily.co/reference#list-rooms). You should see some json, which is the list of rooms on your account.

Your server should now be publicly accessible at the following url:

https://YOUR-PROJECT-NAME.glitch.me

What’s next?

You now have a functional server to make calls to the Daily API which protects your API key. We’ve added a few endpoints as a reference but there are many others you can add as a next step (/recordings for example).

This server also implicitly “trusts” the client that is making these requests. A great next step would be adding some authentication to your client and checking for that on the server. You don’t want just anyone generating tokens with “is_owner” privileges, for example.

Finally, while this is totally viable as a development server, you may want to consider becoming a Glitch member and “Boosting” this app. This gives you a bunch of benefits, most important being that it will always be awake. You will also be supporting the team at Glitch and all the excellent work they do.

[0] I’ve glossed over express and axios. If either of these are unfamiliar, please read their documentation first. At a high level, we’re using express to handle and respond to incoming requests, and we’re using axios to make requests to external Daily APIs.

[1] We’re using async/await to simplify dealing with promises. If this is unfamiliar, do check out the docs on MDN.

Discussion

pic
Editor guide