How To Send Data From Your Nextjs Site to Azure Blob Storage

When building a Next.js application, integrating with external storage can enhance your app's capabilities. Azure Blob Storage is a reliable option, especially when dealing with large amounts of data or files. This tutorial provides a step-by-step guide to connect your Next.js site to Azure Blob Storage, allowing for efficient data transfer between the two.

Understanding Nextjs and Azure Blob Storage

What is Nextjs?

Nextjs is a React framework that allows you to easily build server-side rendered (SSR) websites. It provides many features, such as automatic code splitting, server-side rendering, and easy deployment options.

Nextjs is built on React, a popular JavaScript library for building user interfaces. It extends React's capabilities by adding server-side rendering, which means that the initial HTML of your website is rendered on the server and sent to the client rather than being rendered on the client side using JavaScript. This can improve the performance and SEO of your website.

Nextjs also supports automatic code splitting, meaning your JavaScript code is split into smaller chunks and only loaded when needed. This can improve the loading time of your website, especially for larger applications.

Another critical feature of Nextjs is its easy deployment options. It supports various hosting providers and deployment methods, including static site generation, serverless functions, and traditional server deployment. This flexibility allows you to choose the deployment method that best suits your needs.

What is Azure Blob Storage?

Azure Blob Storage is a cloud-based storage solution provided by Azure. It is a massively scalable object storage solution for unstructured data. It allows you to store and retrieve large amounts of unstructured data in the cloud, such as text or binary data.

Azure Blob Storage is designed to handle large amounts of data, making it suitable for various scenarios, including backup and restore, data archiving, content distribution, and media storage. It provides high durability and availability, ensuring your data is always accessible and protected.

One of the key advantages of Azure Blob Storage is its scalability. You can quickly scale up or down the storage capacity based on your needs without any upfront investment or hardware provisioning. This makes it a cost-effective solution for businesses of all sizes.

Azure Blob Storage also provides rich features, including data encryption at rest and in transit, access control policies, and integration with other Azure services. It supports various data access methods, such as REST APIs, SDKs, and command-line tools, making integrating your existing applications and workflows easy.

Setting Up Azure Blob Storage

To get started with Azure Blob Storage, you need to follow a few simple steps.

Creating a Microsoft Azure account

To use Azure Blob Storage, you must have an Azure account. If you don't have one already, don't worry! Signing up for a free Azure account is quick and easy. Head to the Azure portal, click the "Sign up" button, and follow the instructions to create your account. Once you create your account, you can access a wide range of Azure services, including Blob Storage.

Configuring Blob Storage on Azure

Now that your Azure account is set up, it's time to configure Blob Storage. Follow these step-by-step instructions to create a new Blob Storage account:

  1. Log in to the Azure portal using your Azure account credentials. Once logged in, you'll be greeted with the Azure dashboard, a central hub for managing your Azure resources.
  2. Click on the "Create a resource" button in the top-left corner of the Azure dashboard. This button allows you to create a new resource in Azure.
  3. In the search bar, type "Blob Storage" and select the "Storage account - blob, file, table, queue" option from the search results. This option specifically caters to your Blob Storage needs.
  4. Click on the "Create" button to begin the process of creating a new Blob Storage account.
  5. Fill in the required details for your Blob Storage account. This includes providing a unique account name, selecting a pricing tier that suits your needs, and associating the account with a specific resource group for better organization.
  6. Once you've filled in all the necessary details, click on the "Review + Create" button to proceed to the next step.
  7. Review the settings you've chosen for your Blob Storage account. Make sure everything looks good and meets your requirements.
  8. Finally, click on the "Create" button to create the Blob Storage account. Azure will now provision the necessary resources and set up your Blob Storage environment.

And that's it! You've successfully configured an Azure Storage account. Now you can start leveraging the power of Azure Blob Storage to store and manage your unstructured data. Whether you're building a web application, performing data analytics on big data, or storing backups, Azure Blob Storage provides a reliable and scalable solution for all your storage needs.

Integrating Nextjs with Azure Blob Storage

Installing necessary dependencies

We need to install a few packages before we can integrate Nextjs with Azure Blob Storage. Run the following command to install the necessary package - `@azure/storage-blog`:

SH
npm install @azure/storage-blob

This package supports both JavaScript and typescript. Although we will use Javascript in this tutorial, if you want to use typescript, make sure to install the `typescript` package as well.

Setting up an API endpoint in Next.js

Instead of sending data directly from the front end to Azure (which would expose sensitive credentials), it's a better practice to set up an API route in your Next.js app to handle this. Create a new API route, e.g., `pages/api/upload.js`. Your front end should send requests to this API route, and then you can forward the data to Azure Blob Storage using Azure Blob Storage Javascript SDK methods.

Configuring the connection to Azure Blob Storage from the API route

Next, we need to configure the connection to our Azure Blob Storage account. To do this, you will need your Blob Storage account name and account key. Follow the steps below to configure the connection:

JAVASCRIPT
import { BlobServiceClient } from '@azure/storage-blob';

Next, initialize the BlobServiceClient with authentication using your Blob Storage account’s connection string:

JAVASCRIPT
const AZURE_STORAGE_CONNECTION_STRING = "YOUR_CONNECTION_STRING";
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);

Now you have a client setup that is authenticated using a connection string. But we skipped one thing for the sake of simplicity. We should never commit sensitive credentials like your Azure Storage Connection String to source control. Instead, use .env.local in your Next.js app for local development and provide these as environment variables in your production environment .env.local:

MAKEFILE
AZURE_STORAGE_CONNECTION_STRING=your_connection_string_here

Load the environment variable in next.config.js:

JAVASCRIPT
module.exports = {
env: {
AZURE_STORAGE_CONNECTION_STRING: process.env.AZURE_STORAGE_CONNECTION_STRING,
},
};

Now, use this environment variable in your source code:

JAVASCRIPT
const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
// Create the BlobServiceClient object which will be used to create a container client
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);

Sending data to Azure Blob Storage

Now that we have set up the connection to Azure Blob Storage, we can proceed with sending data from Nextjs to Azure Blob Storage.

We will expand the previous code to use the `BlobServiceClient.upload` function to send the data as follows:

JAVASCRIPT
// pages/api/upload.js
import { BlobServiceClient } from '@azure/storage-blob';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).end();
}
// Get your connection string from env variables or other secure sources
const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
// Create the BlobServiceClient object which will be used to create a container client
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
// Get a reference to a container
const containerName = 'your-container-name';
const containerClient = blobServiceClient.getContainerClient(containerName);
// Create a blob (file) name
const blobName = 'your-blob-name';
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
// Upload data to the blob
const data = req.body; // Assuming you're sending the data as a buffer or string
const uploadBlobResponse = await blockBlobClient.upload(data, data.length);
res.status(200).send(`Upload block blob ${blobName} successfully: ${uploadBlobResponse.requestId}`);
}

Now that your API works, you can initiate this data transfer at the frontend by sending a request to your API route:

JAVASCRIPT
async function uploadToAzure(data) {
const response = await fetch('/api/upload', {
method: 'POST',
body: data,
});
if (!response.ok) {
throw new Error('Failed to upload to Azure Blob Storage');
}
return response.json();
}

That’s it. Now, you have completed the integration steps. This is just a simple quickstart guide. For production, think about the edge cases, handle errors, make sure to test your code, and iterate to optimize the code as you learn more about Azure Blob Storage and Next.js.

Conclusion

You have successfully sent data from your Nextjs site to Azure Blob Storage. You can now use this knowledge to build more advanced applications that require storing and retrieving large amounts of unstructured data. By following the instructions, you may guarantee a smooth data transfer process while combining the agility of Next.js with the infrastructure's robustness of Azure. Always remember to prioritize security and effectiveness above technical settings to keep your program dependable and user-friendly.

Don't want to go through the pain of direct integration? RudderStack's Javascript SDK makes it easy to send data from your Next.js site to Azure Blob Storage.