Cloudinary Blog

Serverless Tutorial: File Storage with Webtask and Cloudinary

By Christian Nwamba
Serverless Tutorial: File Storage with Webtask and Cloudinary

Media makes up the majority of today's website content. While it makes websites more interesting for visitors, media presents challenges because these images and videos are more difficult to store, deliver and manipulate on-the-fly to suit any given situation.

One particularly challenging topic is storage. Traditionally - before the cloud era - FTP was the the go-to solution. We relied on FTP for transferring files to our remote computers. These files are mapped to a URL that we could just deliver to the browser.

What if you have hundreds of images of varying quality and size that need to be stored and delivered. If you do not carefully manage them, storing these files could become difficult, which could lead to unforeseen complexities.

The introduction of cloud storage and hosting helped address the storage problem. Notwithstanding, the cloud (and DevOps engineering generally) still remain a mystery for those of us developers who just write code.

This mystery, however, is about to be solved. Today, we are going to attempt to go completely serverless by deploying Functions to Webtask and storing media files on Cloudinary.

The term serverless does not imply that servers will no longer exist. Rather, it implies that we, the developers, no longer have to care about their existence. We won’t have to set anything up, or bother about IP address and all those terms (like load balancing, containers, etc) that we aren’t accustomed to. We will be able to write and ship functions, as well as upload images to an existing server, for free by creating a Cloudinary account.

Why Serverless

Let's now look in more detail about why you may want to consider this serverless option:

"Serverless" in this article refers to both deployable functions (Function as a Service) and cloud platforms (aka Backend as a Service) like Cloudinary

  • Affordability: Not just serverless, but generally, PaaS, SaaS, IaaS, and *aaS are affordable on a large scale when compared to the cost of doing it yourself. In fact, on a small scale, most services are made free, much like Cloudinary
  • Risk Free: Managing backups, security and other sensitive aspects of your project lifecycle shouldn’t be something you have to worry about. As a developer, your sole job is to write code, so you can focus on that while the platforms take care of these other tasks.
  • Taking the serverless route enables you to focus on what matters in your development cycle as a developer. Sticking to your job of writing code and using simple APIs to store and ship code/assets.

Hosting Functions with Webtask

To get started, let's create a Hello World example with Webtask and see how simple it is.

To do so, we need to install the Webtask CLI tool. The tool requires an account with Webtask so we can create one before installation:

Copy to clipboard
npm install wt-cli -g

Login to the CLI using your sign-up email address:

Copy to clipboard
wt init <Your Email>

Create an index.js file with the following Function as a Service:

Copy to clipboard
module.exports = function (cb) {
    cb(null, 'Hello World');
}

Deploy and run your function:

Copy to clipboard
wt create index.js

Amazing! You have a deployed your app, which now runs on the Webtask server. Go to the URL logged to your console after running the last command to see your deployed app running.

Two things you might want to take note of:

  1. We just wrote a function. A function that takes a callback and sends content as a response. You could already imagine the power.
  2. The create command deploys our app (function) and serves us a URL to interact with.

Let's employ Express to make endpoints which you might be more familiar with:

Copy to clipboard
// ./index.js
var Express = require('express');
var Webtask = require('webtask-tools');
var bodyParser = require('body-parser')
var app = Express();

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// yet to be created
app.use(require('./middleware/cl').config);
require('./routes/galleries')(app);

module.exports = Webtask.fromExpress(app);

Endeavour to install the dependencies: express, webtask-tools, and body-parser.

  • express is a fast Node framework for handling HTTP requests/responses

  • body-parser parses the HTTP request body and exposes it to express req.body

  • webtask-tools simplifies integrating Express and Webtask. No need for the previous function we wrote, we can now write Express routes instead.

Let's create the routes:

Copy to clipboard
// ./routes/galleries.js

module.exports = (app) => {
  app.get('/images', (req, res) => {
      res.json({msg: 'Images are coming soon'})
  });
}

Storing and Delivering Images with Cloudinary

Our next major concern is that Webtask might do a great job at hosting functions, but it may be terrible at file storage, especially media files. Therefore, we need a media storage solution to take care of this for us. Cloudinary offers media storage, but that's not where it shines.

Cloudinary is a media server that manages your media storage and delivery. What’s most impressive is Cloudinary’s ability to transform these media during upload or delivery by simply adjusting the image's delivery URL. Using Cloudinary, you can specify width, height, filters, overlays, and enable a lot of other cool features by editing an image/video transformation URL, which you can learn about here.

To use Cloudinary effectively, we recommend using the SDKs rather than interact with the APIs directly (which you are allowed to do). You can install the SDK to your current project:

Copy to clipboard
npm install --save cloudinary_js

You also need to create a FREE Cloudinary account to get credentials that you will supply to the SDK in order to interact with Cloudinary.

Configuring Cloudinary with Webtask Context

Webtask allows you to dynamically adjust its behavior based on the information provided via the Webtask context. We could use the context to maintain dynamic state of our application. Things like query parameters, secrets and environmental variables are a good fit for what could live in the Webtask context. Speaking of environmental variables, let's rely on those to configure Cloudinary:

Copy to clipboard
// ./middlewares/cl.js
var cloudinary = require('cloudinary');

module.exports = {
    config: (req, res, next) => {
        cloudinary.config({
            cloud_name: req.webtaskContext.secrets.CL_CLOUD_NAME,
            api_key: req.webtaskContext.secrets.CL_API_KEY,
            api_secret: req.webtaskContext.secrets.CL_SECRET
        });
        req.cloudinary = cloudinary;
        next()
    },
}

A simple Express middleware that configures an instance of cloudinary using credentials provisioned via the Webtask Context Secret. While running the functions, you are expected to supply the credentials:

Copy to clipboard
wt create index --secret CL_CLOUD_NAME=<CLOURINARY_CLOUD_NAME> --secret CL_API_KEY=<CLOURINARY_API_KEY> --secret CL_SECRET=<CLOURINARY_API_SECRET> --bundle --watch

Remember to fetch the credentials from your Cloudinary dashboard.

Notice how we are passing each credential using the --secret option, as well as telling Webtask to bundle our file and watch for changes using --bundle and --watch flags, respectively. Bundling is only necessary when you have multiple local modules.

Uploading Images to Cloudinary

Now that we have everything configured, let's store our image on Cloudinary by uploading it from our computers. We can do this by adding an endpoint that its logic will process the image and send it to Cloudinary using the SDK:

Copy to clipboard
// ./routes/galleries.js
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

module.exports = (app) => {
    ...
    app.post('/images', multipartMiddleware, (req, res) => {
        console.log(req.files)
          req.cloudinary.uploader.upload(req.files.image.path, function(result) {
             res.status(200).send('Image uploaded to Cloudinary')
         });
     })
}

When the image arrives from the client, it is parsed and processed with multipart and uploaded to Cloudinary using the upload method. Remember that req.cloudinary is provided via the middleware we created earlier.

Source Code

Notice how stayed away from creating any local host/server and built everything using the actual environment that our code and media will live. This is where the power of serverless lies.

Cloudinary exposes lots of APIs and transformation options that you can learn about in the documentation. Feel free to dig these docs and find what suits your situation.

Christian Nwamba Christian Nwamba (CodeBeast), is a JavaScript Preacher, Community Builder and Developer Evangelist. In his next life, Chris hopes to remain a computer programmer.

Recent Blog Posts

Generate Waveform Images from Audio with Cloudinary

This is a reposting of an article written by David Walsh. Check out his blog HERE!
I've been working a lot with visualizations lately, which is a far cry from your normal webpage element interaction coding; you need advanced geometry knowledge, render and performance knowledge, and much more. It's been a great learning experience but it can be challenging and isn't always an interest of all web developers. That's why we use apps and services specializing in complex tasks like Cloudinary: we need it done quickly and by a tool written by an expert.

Read more
Make All Images on Your Website Responsive in 3 Easy Steps

Images are crucial to website performance, but most still don't implement responsive images. It’s not just about fitting an image on the screen, but also making the the image size relatively rational to the device. The srcset and sizes options, which are your best hit are hard to implement. Cloudinary provides an easier way, which we will discuss in this article.

Read more

The Future of Audio and Video on the Web

By Prosper Otemuyiwa
The Future of Audio and Video on the Web

Web sites and platforms are becoming increasingly media-rich. Today, approximately 62 percent of internet traffic is made up of images, with audio and video constituting a growing percentage of the bytes.

Read more

Embed Images in Email Campaigns at Scale

By Sourav Kundu
Embed Images in Email Campaigns at Scale

tl;dr

Cloudinary is a powerful image hosting solution for email marketing campaigns of any size. With features such as advanced image optimization and on-the-fly image transformation, backed by a global CDN, Cloudinary provides the base for a seamless user experience in your email campaigns leading to increased conversion and performance.

Read more
Build the Back-End For Your Own Instagram-style App with Cloudinary

Github Repo

Managing media files (processing, storage and manipulation) is one of the biggest challenges we encounter as practical developers. These challenges include:

A great service called Cloudinary can help us overcome many of these challenges. Together with Cloudinary, let's work on solutions to these challenges and hopefully have a simpler mental model towards media management.

Read more

Build A Miniflix in 10 Minutes

By Prosper Otemuyiwa
Build A Miniflix in 10 Minutes

Developers are constantly faced with challenges of building complex products every single day. And there are constraints on the time needed to build out the features of these products.

Engineering and Product managers want to beat deadlines for projects daily. CEOs want to roll out new products as fast as possible. Entrepreneurs need their MVPs like yesterday. With this in mind, what should developers do?

Read more