The Couchbase DevRel team has been working with the Bad Website Club on freeCodeCamp materials. 

freeCodeCamp is a non-profit organization that consists of an interactive learning web platform, an online community forum, chat rooms, online publications and local organizations that intend to make learning software development accessible to anyone.

The Bad Website Club is an online community helping new learners in their programming journey.

We have been streaming to show fCC learners what could happen to their project in more ‘real-life’ conditions. We started with the Responsive Web Design course, took some examples like the Survey form, completed them and pushed them to production. The whole series is streamed on YouTube, LinkedIn, Twitter and Twitch, and the recordings are available on this youtube playlist if you want to check it out: New Couchbase Streams: Starting July 31st!

I was personally streaming on the Survey project. In this blog post series, I will show you all the additional steps you can do publish the code on GitHub, deploy the Survey online with Netlify, and storing its content on Couchbase Capella.

Step 1 – Create an HTML Form

Getting a lot of inspiration from the FreeCodeCamp survey example (copy, paste, and trim), I get the following HTML form. It’s a bit simpler than the original one.

The styles.css file is exactly the same than the original. Open here to see the survey form in action. You can open in your browser, right click on the page and you should see something like view page source or inspect. Click on that and this will open a panel which shows the code of the page. While you are in this view you can click on link like style.css or click on the styles tab to view the CSS applied to certain elements as well.

To test this code sample you can first clone this repository to your local computer using the terminal or you can download it as a zip file).

Screenshot of button in github where you can clone or download code

Go to your browser and on the top bar select file, open, than select the index.html file from the folder (or zip folder) that was downloaded. Take a look at your browser URL, it shows a path to a local file. And you should see something like this, that does not do anything when you click on submit.

The screenshot of the survey from created during the freecode camp Survery lesson

The question then is, how do we deploy it to the Internet, how do we make it do something? We need some backend code to be executed after the click. And then make that code store the form content in the database.

Step 2 – Git, Github, Netlify

Let’s start by deploying this form live on the Internet. To that end we are going to use Netlify. First thing first, making sure that we have the Netlify CLI available, and that we are logged in. If it’s not installed, the fastest route is to type in your terminal:

You wil find more details in the Netlify get started docs.

Typing netlify version in my terminal currently gives me netlify-cli/15.6.0 win32-x64 node-v18.5.0. So I know it’s installed and ready.

Then the next thing to do is type netlify login in your terminal. It will take you through the Netflify sign in form.

Now everything should be ready to move to the deployment phase. But just to make sure we are going to test things locally. Because that’s what most developers do. To that end, type netlify dev in your terminal.

It should output the following in your terminal and open your form in your browser.

If you take a look at the browser URL bar again, you will see that it is different. It looks like a webite address, not a local file. Congratulations, you just run your first local server, serving your HTML and CSS file, using Netlify dev! You have a website running on your machine. Now let’s make this accessible to everyone on Internet, both the source code and the site itself.

Go to GitHub (or GitLab, or Heptapod, or any other code source hosting solutions, there are others out there!) and create a new Repository. Visit https://github.com/new for Github. You are now in the repo wizard creation. I have only setup my organization, my repo name and a description than clicked on the Create Repository button.

A screenshot of Github's repository creation wizard

A screenshot of a newly intitialized Github repo

It will give you all the instructions needed to convert your working folder in a git repo, and link it to your GitHub project. This is what I typed in my terminal (you can either copy and paste the below into your terminal or press enter after each line of the below to have it execute. Note, you will have to change line 6 to be your project repository URL):

This is the resulting terminal output:

 

Now if I go back to the Github page and reload it, this what I see:

A screenshot of the github repository after an intial commit was pushed

Congratulations, your code is now available on Github, for everyone to see, learn from, contribute to. It’s now time for Production! Let’s make that website live 💪

Go ahead and visit https://app.netlify.com/start/deploy. This will get you to Netify’s new project wizard. You will see various buttons to help you start, GitHub, GitLab, Bitbucket, AzureDevops. Let’s click on GitHub.

A screenshot of the Netlify Wizard for new project creation

You will see a couple windows asking you to link your GitHub profile to Netlify. Go ahead and proceed, it will take you to the following page.

A screenshot of the second step of Netlify's project creation wizard after picking Github

Netlify is telling me I have no Netlify app installed on any GitHub org. Click on Configure Netlify on GitHub, it will open a poup window asking you to select the GitHub org you want to install Netlify in, and which repo to give it access to.

A screenshot of Github's authorization matrix

I leave the default and proceed to the next step. From now on you should see every repo in your GitHub account.

A screenshot of Netlify's project List showing linked Github project

I will leave the default and click on Deploy myproject:

A screenshot of the default Netlify project configuration

 

You will see a link to your newly deployed on the internet website, for me it’s https://jolly-sfogliatella-3e6c07.netlify.app/. Netlify provides sandboxes environment under the netlify.app domain for you to deploy things without having your own domain name.

A screenshot of a newly created Project

Congratulations, your website is now live on the Internet. Take a minute to celebrate 🎉.

Now we can link this Netlify project by entering netlify link in the terminal. A list of options will be offered. Select the default one, which should be Use current git remote origin (https://github.com/yourOrg/yourProject). Because you have deployed through GitHub, Netlify has the git information of your repo and can infer which project to use (and also at that point you probably have only one project). This is what the output looks for me:

We can try a couple things now. I am going add a 🐼 emoji to my form because why not. In index.html, I am modifying line 9 from this: <h1 id=”title” class=”text-center”>Survey Form</h1> to this <h1 id=”title” class=”text-center”>Survey Form 🐼</h1>

I then save the file, and push this changes to Github. Then, in the terminal, I type netlify open:site:

Something very cool is happening. Because your GitHub repo is linked to Netlify, a new deployment will be automatically done by Netlify. So when opening the website, you will see the Panda <3.

At that point we have a Github Repository that holds our code, that is integrated to Netlify, that will automatically create new deployment when you push new code. And we also have a configured netlify CLI in our working folder. We are ready to write backend code!

Step 3 – Backend

In this chapter we will answer the following question: What happens when someone fill the form and click on submit ?

The answer right now is: Nothing. Let’s change that. By writing some JavaScript. We are going to display a popup alert when someone enters valid information and click on Submit. In your index.html file you will put the following <script> code between the last closing div tag </div> and before the closing body tag </body>. 

 

If you save your code and reload the page, fill the form, click on submit, you should see something like this:

A screenshot of a sucessfull form submission

Now that we have something happening when a user submits the form, let’s go a bit further. We want to look at the content of the form and make sure we can get the right data in JSON. We want a string for the name, and integer for the age and a boolean for the recommendation.

And it turns out that the HTML checkbox is not playing nice. The value it gives by default is no value, and once checked it gives the content of the value field. We are going to add another input field, hidden, to make sure the default value will be False.

Now about the JavaScript Code, the are some interesting new lines to look into.

With that being sorted, let’s get serious and start creating a Netlify function. Enter netlify function:create in your terminal. You should see something like:

Select Serverless function, leaves the default for the next question about path, keep JavaScript as the language, keep the default hello-world template, than give a name to your function. Mine is called saveform. This will generate new files in the netlify folder. If you run netlify dev now, you will see new lines in the logs:

This means that our netlify dev server is also serving our newly created function. Take a look at the newly generated file ./netlify/functions/saveform/saveform.js.

Let’s try it out by calling this function when the user clicks on submit. Just add the following code after the last console.log call:

Add, commit and push. netlify open:admin

A screenshot showing the Netlify site administrator overview, with the list of all deployments already done

A screenshot of the form page and the developer tools opened, showing the message returned by the Netlify function

At this point, you have a frontend and a backend deployed, on the Internet. But all we are doing is calling the default function created by Netlify’s wizard. The next step is to send the content of the form to that function, and store it in a database.

Step 4 – Database

First thing to do is figure out how to send the form details to the function. This requires us to change our GET method to a POST method. These things are called HTTP request methods, sometimes reffered to as HTTP verbs. You can take a look at the full list on MDN. A Get method request is used to only retrieve data. A post method request is used to create or change data. This is exactly what we want. We want to create a new entry in our Dababase when someone submits a form. An HTTP request has a method, some headers(Metadata about your requests, here we are saying the request will be JSON content with the Content-Typ header), and a body. The body of our request will be JSON text.

Our frontend HTTP request to our backend is changed, now we need to adapt the backend code.

 

You should see a different message in the web dev console, you should see {“name”:”yourName”}.

We have sent the form data to the backend and made sure of it. Now on to the database side of things. Working at Couchbase, this is the database I am going to use. A simple way to try, go to https://cloud.couchbase.com/sign-up, create an account, you get a 30 day trial, no credit card required.

A screenshot of the first Couchbase Capella Get started wizard step

You can leave the default on, or choose your favorite cloud provider and closest region. Click on Deploy now and wait for the deployment of your database.

A screenshot of the Couchbase Capella trial home

Two things we want to do from there. Make sure we can connect to that database from our backend code, and make sure we can write the data somewhere. Go ahead and click the Connect tab.

In Couchbase we store data in Buckets. By default the trial comes with a travel-sample bucket preimported. We are not going to use it. Instead we are going to create our own bucket. Click on Settings on the top level menu, than on Buckets on the left menu.

A screenshot of the Bucket settings in Couchbase Capella

Now click on + Create Bucket, give it a name and leave the rest to default settings.Than Click on Create Bucket.

A screenshot of the Buckets settings home, with the newly created bucket visible

We have a new Bucket, now we need to create associated credentials. Click the Database Access button, than Create Database Access button.

A screenshot of the empty Credentials settings

A screenshot fo the credentials creation detail

Make sure you remember both username and passaord and click on Create Database. One last thing to do is to allow this database to be reachable publicly. Right now it’s hidden. Click on Allowed IP Addresses, than Add Allowed IP. Click on Allow Access from Anywhere, follow the instructions. This should prefill the form, than click on the Add Allowed IP button. You might think this is a bit cumbersome. Why isn’t it the default?

A screenshot of the Allow Access from Anywhere popup

A screenshot of the resuting operation with the newly added IP range

Now click on the Connect tab. You will see the Connection String, select your database credentials, switch the language to Node, and it will give us the right instructions to connect to the database from our backend code.

A screenshot of the SDK connection instructions, with doc and code

We can copy and paste this to our function code, and add a couple more things:

For Couchbase you need to install it. Running npm i couchbase@4.2.4 will do the trick. Right now Netlify/Couchbase compatibilty is assured for Couchbase version 4.2.4 or below. This is due to the nature of our SDK. It’s a JavaScript interface on top our our C SDK. And C dependencies expect to find their system dependencies in the right version. Right now Couchbase 4.2.5 is expecting to find GLIBC_29 but it’s not available on the Ubuntu system running our Netlify backend code.

Now that we have dependencies, let’s be explicit in how build them. You can add a netlify.toml file at the root of the repository with the following content:

It’s doing a couple things. Installing the dependencies and removing the debug symbol table from couchbase_impl.node. This file is the C library used by our Node SDK. And it’s too big for Netlify right now. So we are removing unnecessary clutter coming from the build process.

Now you could add the new files, commit and push to GitHub. But that would push your password to GitHub. We don’t want that. Instead you can test it by running netlify dev. Go ahead and resubmit the form.

If everything went well, you have written data to your Database! You can check this out easily by going to the Couchbase Capella UI. Cick on Data Tools, select your Bucket, Scope and collection, and you should see your survey from document.

This is great, you just wrote code to connect your database!

Step 5 – Configuration Management

To avoid pushing our credentials on GitHub, we are going to use environment variables. Environment variables are common to every Operating Systems and is the best way to manage configuration across different environments (different OSs, clouds, test, staging, preproduction, production, whatever fits your workflow).

On Mac or Linux, you can run export MYVARIABLE=”value” in your terminal. On Windows you can run $Env:MYVARIABLE=”value”

To define them in Netlify’s context, you can go though the UI and do it manually, or use the CLI:

Now you can add your files, commit and push your code. Congratulations, you went fullstack. Backend, Frontend and Database. And deployed everything live! But our work is not over. There are still a couple things we can do to make this more professional.

Step 6 – User feedback

Right now we don’t have much happening when the user clicks on the Submit button of our form. We need to change this to let them know they have been successfully recored, or not. First step it check for an error on the dev side of things. HTTP status code are well made, anything equals or higher than 400 is usually an error, so we can do something like this:

To test it, just make a typo somewhere in your Connection String or Credentials to Couchbase. You should see errors in the webconsole once clicking on Submit. But the web console is just for us, we need to add a proper error or success message to our user.

I added a couple span HTML elements with error and success message right before the end of the form. Note the hide CSS class that makes them invisible for now.

And here is the corresponding CSS. Displaying the error in red, hiding or showing an element, and a nice fade-out animation because I am fancy like that.

Now to put everything together. The first two lines get the new span elements just added. The call to form.reset() is clearing all values from the form when the returned response status code is 200. Than the rest is playing with CSS classes to make the message appear, than fading out with the addition of the fade-out class, than a 7000ms timeout function will remove every classes and hide the element again. It’s pretty much the same when there is an error.

Now you can test submit a form again and see the different success or error message, depending on what you decided to do. When you are happy you can add, commit and push that code.

Congratulations, you made it to the end of this guide! You have used git, GitHub, Netlify and Couchbase Capella to deploy an HTML form on the web, and made sure that the content was stored in a database each time users submit the form.

Ready for more?

Author

Posted by Laurent Doguin, Developer Advocate, Couchbase

Laurent is a Paris based Developer Advocate where he focuses on helping Java developers and the French community. He writes code in Java and blog posts in Markdown. Prior to joining Couchbase he was Nuxeo’s community liaison where he devoted his time and expertise to helping the entire Nuxeo Community become more active and efficient.

Leave a reply