# Serverless Architecture for Backend

### **What are Backend Server?**

As a developer, you probably build the frontend app or web app using basic Technology like HTML, CSS, Javascript, and React (Javascript library) you can easily deploy them using famous platforms like Vercel, Netlify, and many more. but in the case of deploying the backend server is like **a snowball's chance in Hell.**

If you know some Backend then you might use `express` to create the Backend server and run it usually `node index.js` which starts a process on a certain port whatever you defined.

**If you want to deploy it on the internet, there are a few ways-**

**i. AWS ii. GCP \[Google Cloud Platform Services\] iii.Azure iv. Cloudflare**

## HOW?

1. Rent a VM (Virtual Machine) and deploy your app.
    
2. Put it in an Auto-scaling group
    
3. Deploy it in a Kubernetes cluster
    

**Don't worry if don't get any idea about these we will discuss everything further.**

**Everything and Everyone has pros and cons similar to the downside of this is-**

1. Taking Care of how/when to scale.
    
2. You have to pay the base cost even if no one is visiting your website
    
3. Monitoring various servers to make sure no server is down
    

### What if, you could just write the code and someone else could take care of all of these problems?

# **What are**`serverless` Backends

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709401677691/baad795a-bd2f-4468-a144-aee21d692a18.png?auto=compress,format&format=webp align="left")

### **Definition:**

What if you could just write your `express routes` and run a command. The app would automatically

1. Deploy
    
2. Autoscale
    
3. Charge you on a `per request` basis (rather than you paying for VMs)
    

As I told you everything in this world has pros and cons so this also has some cons but these cons or problems are very important to know.

1. ### More Expensive at scale: -
    

As the backend system grows bigger, it costs more money to manage and maintain it properly.

2. ### Cold start problem: -
    

"Delayed response when serverless function or microservice is inactive or newly initialized."

**There are many famous backend serverless providers -**

<details data-node-type="hn-details-summary"><summary>AWS Lambda</summary><div data-type="detailsContent"></div></details>

[**https://aws.amazon.com/pm/lambda/?trk=5cc83e4b-8a6e-4976-92ff-7a6198f2fe76&sc\_channel=ps&ef\_id=CjwKCAiAt5euBhB9EiwAdkXWO-i-th4J3onX9ji-tPt\_JmsBAQJLWYN4hzTF0Zxb084EkUBxSCK5vhoC-1wQAvD\_BwE:G:s&s\_kwcid=AL!4422!3!651612776783!e!!g!!aws lambda!19828229697!143940519541**](https://aws.amazon.com/pm/lambda/?trk=5cc83e4b-8a6e-4976-92ff-7a6198f2fe76&sc_channel=ps&ef_id=CjwKCAiAt5euBhB9EiwAdkXWO-i-th4J3onX9ji-tPt_JmsBAQJLWYN4hzTF0Zxb084EkUBxSCK5vhoC-1wQAvD_BwE:G:s&s_kwcid=AL!4422!3!651612776783!e!!g!!aws%20lambda!19828229697!143940519541)

<details data-node-type="hn-details-summary"><summary>Google Cloud Functions</summary><div data-type="detailsContent"></div></details>

[**https://firebase.google.com/docs/functions**](https://firebase.google.com/docs/functions)

<details data-node-type="hn-details-summary"><summary>Cloudflare Workers</summary><div data-type="detailsContent"></div></details>

[**https://workers.cloudflare.com/**](https://workers.cloudflare.com/)

But we will use Cloud-flare for this :

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709402750440/b5df9fda-c0db-4eb9-a9bb-ae769c72340d.png?auto=compress,format&format=webp align="left")

Just go on the Cloudflare website and sign up if you are new you will get to see something like this. before we proceed there is a big question that arises which is:-

# **When should you use a serverless architecture?**

1. **When you want Quick Launch:**
    
    * Serverless lets you start your app fast without server setup worries. It's like moving into a ready-to-use office.
        
2. **When you want Automatic Scaling:**
    
    * It adjusts to traffic changes automatically. Think of it as a store that expands or shrinks based on customers, saving costs.
        
3. **When you want Cost Optimization:**
    
    * You pay only when your code runs, making it cost-effective for low-traffic apps. It's like paying for electricity only when you use it, keeping bills low.
        

### Few senior developers want to know how Cloudflare workers work.

For detailed blog post click here:- [**Blog on Workers**](https://developers.cloudflare.com/workers/reference/how-workers-works/#:~:text=Though%20Cloudflare%20Workers%20behave%20similarly,used%20by%20Chromium%20and%20Node)

they can read this blog for more detail i also mentioned some important glimpses from the blog:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709403773795/27c2a923-68e3-40d6-8fac-0746e4760484.png?auto=compress,format&format=webp align="left")

I think You know enough to start using Cloudflare. Don't worry, just follow my steps carefully, and you'll learn how to set up the backend without any problems.

* Create a directory with a name whatever you want suppose we created a directory with name practice.
    
* Open this directory in the code Editor whatever you use
    
* Open the terminal in the code editor and write this command for initializing the Cloudflare init the command is:-
    
    **COPY**
    
    **COPY**
    
    ```basic
       npm create cloudflare
    ```
    

now select the "Hello World" workers as we just Learning.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709404685701/5c1afd00-d1a3-41cf-839c-0eac9047de96.png?auto=compress,format&format=webp align="left")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709404746315/399c9a3f-4aa5-40cc-bc39-51c37f4d04db.png?auto=compress,format&format=webp align="left")

As I know the typescript I preferred to use typescript. if you don't then relax there is not to worry

***After that, they ask you:***

* **Do you want to deploy your application?** Select the NO because we will deploy the backend using `npm run deploy`
    
* **Explore package.json dependencies**
    
    **COPY**
    
    **COPY**
    
    ```basic
      "wrangler": "^3.0.0"
    ```
    
    Notice `express` there is no dependency on there
    
* **Start the worker locally and write this in the directory where package.json exists**
    
    **COPY**
    
    **COPY**
    
    ```basic
      npm run dev
    ```
    
    After that, your terminal will look like this now just press ctrl and on the localhost:8787:-
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709405486182/b449a7c0-922e-4a87-beec-f586b5e285c3.png?auto=compress,format&format=webp align="left")
    
    You can see you are directed to the browser where Hello World is written.
    
* Open src file you'll see this:
    
* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709406033049/d7c25d85-1356-4220-9e92-bf1b2cdaed59.png?auto=compress,format&format=webp align="left")
    
    ### **Question - Where is the express code? HTTP Server?**
    
    Cloudflare expects you to just write the logic to handle a request. Creating an HTTP server on top is handled by Cloudflare
    
* ### **Question - How can I do**`routing` ?
    
    In express, routing is done as follows -
    
    **COPY**
    
    **COPY**
    
    ```basic
      import express from "express"
      const app = express();
    
      app.get("/route", (req, res) => {
          // handles a get request to /route
      });
    ```
    
    This is how you can do the same in the Cloudflare environment.
    
    **COPY**
    
    **COPY**
    
    ```basic
      export default {
          async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
              console.log(request.body);
              console.log(request.headers);
    
              if (request.method === "GET") {
                  return Response.json({
                      message: "you sent a get request"
                  });
              } else {
                  return Response.json({
                      message: "you did not send a get request"
                  });
              }
          },
      };
    ```
    
    Don't worry if you see this code; it's just for reading purposes. We won't use it. This code shows how to create a GET request using Cloudflare Workers, but we won't use it because Cloudflare Workers use their library, not Node.js or any other common libraries. Writing code with this library can be challenging.
    
* Lets Deploying a worker
    

Now that you have written a basic HTTP server, let’s get to the most interesting bit — `Deploying it on the internet`

We use Wrangler Dont worry I'll tell you

Step 1 Log in to Cloudflare via the Command Line Interface `npx wrangler login` Nothing just type this in the terminal of the code editor where the project is going on.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709407099276/e2cdc4c2-5e9d-4d69-b3f2-72697bf077df.png?auto=compress,format&format=webp align="left")

you'll see something like this.

Step 2 Deploy Your Worker:

**COPY**

**COPY**

```basic
npm run deploy
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709407183250/608eddb3-5740-4c55-a1de-611910039c62.png?auto=compress,format&format=webp align="left")

After this, you'll see something like this

---

**This is optional and just to know:-**

### **Assigning a custom domain**

You have to buy a plan to be able to do this

You also need to buy the domain on Cloudflare/transfer the domain to Cloudflare

![notion image](https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F2cde6fd6-3b5e-40db-92dd-8dd42d78072b%2FScreenshot_2024-02-10_at_4.06.21_AM.jpg?table=block&id=48d79027-bffe-4c5a-a308-582671ab0098&cache=v2 align="left")

---

Come back to the topic If you now go back to the website it will show you this means that u deployed your application for now ignore my-app the app we deploy is calm-sun-10b3

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709407742682/39f44491-d9b1-4387-9a48-d4b406716c81.png?auto=compress,format&format=webp align="left")

* **Now come back to the very important question which is whether we always use this challenging worker syntax or we have something else to tackle this problem.**
    

### Why can’t we use express?

Now you might be thinking **Why does Cloudflare doesn’t start with a simple express boilerplate?** the answer to this Question is very simple:

* **Express heavily relies on Node.js**
    

**The answer to this big question is:**

### **Using Hono**

You must read this Because this will give you the answer to all the questions you have in your mind:-

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709408397863/73f695b3-974d-4635-b66a-10329e3441c4.png?auto=compress,format&format=webp align="left")

**What runtime does it support:**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709408552394/4a194390-f7bf-41a1-a0a4-25339d9a6560.png?auto=compress,format&format=webp align="left")

**Using Hono is easy:-**

### Initialize a new app

**COPY**

**COPY**

```basic
npm create hono@latest my-app
```

1. Move to `my-app` and install the dependencies.
    

**COPY**

**COPY**

```basic
cd my-app
npm i
```

1. Hello World
    

**COPY**

**COPY**

```basic
import { Hono } from 'hono'
const app = new Hono()

app.get('/', (c) => c.text('Hello Cloudflare Workers!'))

export default app
```

### **Getting inputs from the user**

**COPY**

**COPY**

```basic
import { Hono } from 'hono'

const app = new Hono()

app.post('/', async (c) => {
  const body = await c.req.json()
  console.log(body);
  console.log(c.req.header("Authorization"));
  console.log(c.req.query("param"));

  return c.text('Hello Hono!')
})

export default app
```

*If you are here and learning the serverless Backend so you know what is Postman and how to use it now just do one thing.*

* Go on the Postman and write the localhost(URL) above
    
* Select the POST from the options
    
* Write any value in the headers with the key Authorization and query param.
    
* Now click on the Send Button.
    
* You can see the output in the console if there is an error try to fix it.
    

### **Deploying**

Make sure you’re logged into Cloudflare (`wrangler login`)

**COPY**

**COPY**

```basic
npm run deploy
```

# **Middlewares**

### **Creating a simple auth middleware**

Middleware is very important in the backend this is how you define the middleware in the backend.

**COPY**

**COPY**

```basic
import { Hono, Next } from 'hono'
import { Context } from 'hono/jsx';

const app = new Hono()

app.use(async (c, next) => {
  if (c.req.header("Authorization")) {
    // Do validation
    await next()
  } else {
    return c.text("You dont have acces");
  }
})

app.get('/', async (c) => {
  const body = await c.req.parseBody()
  console.log(body);
  console.log(c.req.header("Authorization"));
  console.log(c.req.query("param"));

  return c.json({msg: "as"})
})

export default app
```

Notice you have to return the `c.text` value.

### "As you can see, coding in Hono is quite similar to using Express. Hono is an excellent library for writing code in Cloudflare Workers and deploying the backend. That wraps up this blog. Thank you for reading!".
