Cloudinary & Image Storage
In this lesson and module, we'll investigate to see if there's a better way of storing the newly created images for listings in our database. We'll discuss and investigate cloud-based image and video management services and see how we can use Cloudinary for our application.
📝 A sample of the
.envfile in our server project, after this lesson is complete, can be found - here.
Let's go to the
/user/:id route of of our own profile page in our application and examine the listing we've recently created in the last module. If we survey the data returned from our
Query.user GraphQL field in our network inspector, we can see that the listing we just created has the base64 encoded version of the image file as the image data.
If we were to survey the
"listings" collection in MongoDB Atlas and find the same recently created listing, we can see the same base64 encoded string in the image field.
This shouldn't be surprising because that is what we told our server to do. We encoded an image file in the client and sent the encoded image as a string to our server to be stored in our database. Thus, when we request listing data, the
listing.image field will return the base64 encoded string directly from our database.
Although there is nothing wrong with this method of storing images, it isn't ideal. There are two inherent flaws with this:
Images can take a lot of storage space in our database. Image files by nature are large. In addition, by base64 encoding the binary image files into a string, it actually increases the size of the source image by about 33%. The
imagefield takes up more space than the rest of the fields of a single listing document combined.
If all our listings had base64 images, transmitting and querying all that image data in our GraphQL queries will slow down our response time which can make our app feel laggy and un-optimized.
This is where a cloud-based image and video management service comes in! These services store our images for us on the cloud and all we need to do is save the URL link of the image in our database instead of the image itself. If our app was to even have videos, these services can help store videos as well.
All major applications we use day-to-day use a cloud-based image and video management service. For example, let's check out Airbnb. We can visit one of a certain listing and look for the image in the document inspector.