How to Integrate Shiprocket API into an E-commerce Website Using Node.js and React
Shipping automation is an important part of building a successful e-commerce application. When an online store receives orders, managing shipments, generating shipping labels, assigning couriers, and tracking deliveries manually can become time-consuming.
The Shiprocket API helps developers automate these tasks by integrating shipping functionality directly into an e-commerce platform.
In this tutorial, we’ll explore how to integrate Shiprocket into an e-commerce website using a React.js frontend and a Node.js/Express backend.
What Is the Shiprocket API?
Shiprocket provides shipping-related API capabilities that can help e-commerce businesses manage shipment creation, courier assignment, shipping labels, and tracking.
By integrating the API, developers can connect an online store with shipping workflows without requiring users to manage every step manually.
Prerequisites
Before starting, make sure you have:
- Basic knowledge of JavaScript and REST APIs
- Node.js and npm installed
- A React.js application
- A Node.js/Express backend
- A Shiprocket account with API access
- Your Shiprocket API credentials
Important: Keep your API credentials on the backend. Never expose authentication credentials or private tokens in React frontend code.
Step 1: Set Up Your Node.js Backend
Create a project directory and install the required packages.
mkdir shiprocket-integration
cd shiprocket-integration
npm init -y
npm install express axios dotenv cors
Create an index.js file and configure your Express server.
const express = require("express");
const axios = require("axios");
require("dotenv").config();
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send("Shiprocket integration server is running");
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
This creates a basic backend that will handle communication between your e-commerce application and Shiprocket.
Step 2: Configure Your Environment Variables
Create a .env file in your backend project:
SHIPROCKET_EMAIL=your_registered_email
SHIPROCKET_PASSWORD=your_password
PORT=5000
Add .env to your .gitignore file so credentials are not committed to your repository.
For production applications, use a secure secrets manager and follow your organization's credential-handling policies.
Step 3: Authenticate With Shiprocket
Your backend needs an authentication token before it can make authorized API requests.
The following example illustrates the login request using Axios:
async function getShiprocketToken() {
const response = await axios.post(
"https://apiv2.shiprocket.in/v1/external/auth/login",
{
email: process.env.SHIPROCKET_EMAIL,
password: process.env.SHIPROCKET_PASSWORD,
}
);
return response.data.token;
}
This function sends the configured credentials to the authentication endpoint and returns the token from the response.
Handle authentication failures, token expiration, and credential errors in your application. Check the current Shiprocket API documentation for the applicable authentication requirements.
Step 4: Create a Shipment
Once authentication is complete, your backend can send order information to Shiprocket.
A typical shipment workflow may require information such as:
- Customer name and contact details
- Delivery address and PIN code
- Order ID and order date
- Product details, quantities, and prices
- Package dimensions and weight
- Payment and shipment information
Here is an illustrative Express route:
app.post("/api/shipments", async (req, res) => {
try {
const token = await getShiprocketToken();
// Validate and prepare the order data before
// sending it to the Shiprocket API.
const orderData = req.body;
const response = await axios.post(
"https://apiv2.shiprocket.in/v1/external/orders/create/adhoc",
orderData,
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
res.status(201).json(response.data);
} catch (error) {
console.error(
"Shipment creation failed:",
error.response?.data || error.message
);
res.status(500).json({
message: "Unable to create shipment",
});
}
});
Before using this route in production: validate the incoming request, construct the payload according to Shiprocket's current API schema, authenticate the customer, and ensure the order belongs to your application. Do not blindly forward arbitrary client-supplied order data to the shipping provider.
Step 5: Connect the React Frontend
Your React application can call your own backend endpoint to initiate shipment creation.
async function createShipment(orderData) {
const response = await fetch(
"http://localhost:5000/api/shipments",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(orderData),
}
);
if (!response.ok) {
throw new Error("Failed to create shipment");
}
return response.json();
}
Call this function from your checkout or order-management workflow after the order has been validated.
For a production deployment, configure the backend URL appropriately, add authentication and authorization, and display meaningful success or error messages in the interface.
Step 6: Manage Courier Assignment and Shipping Labels
After creating an order or shipment, your application may need to support additional shipping operations, such as:
- Checking available courier services
- Assigning a courier
- Generating or retrieving an Air Waybill (AWB)
- Generating shipping labels
- Scheduling pickups
These operations generally require additional API calls and may depend on shipment status, pickup availability, serviceability, and account configuration.
Implement each operation as a separate backend service or route, following the current Shiprocket API documentation for the correct endpoints and request formats.
Step 7: Add Shipment Tracking
Customers expect to know where their orders are and when they may arrive.
You can extend your e-commerce application with a tracking page that displays shipment status and relevant tracking details retrieved through the appropriate Shiprocket API.
For example, your backend could expose an application endpoint such as:
app.get("/api/shipments/:shipmentId/tracking", async (req, res) => {
try {
// Verify the user's access to this shipment.
// Retrieve tracking information through the
// appropriate Shiprocket API endpoint.
// Return only the relevant tracking details.
res.json({
message: "Implement tracking using the current Shiprocket API",
shipmentId: req.params.shipmentId,
});
} catch (error) {
res.status(500).json({
message: "Unable to retrieve tracking information",
});
}
});
This is a route structure example, not a complete tracking integration. Replace the placeholder with the documented tracking endpoint and its required parameters.
Step 8: Handle Webhooks and Shipment Updates
Polling an external API repeatedly is not always the most efficient way to keep shipment information up to date.
Where supported by your Shiprocket account and API configuration, webhooks can help your application receive shipment-related events.
A robust webhook implementation should:
- Validate incoming events according to the provider's supported verification mechanism.
- Update the corresponding shipment record in your database.
- Handle duplicate events safely.
- Log failures and support retries where appropriate.
- Avoid exposing sensitive customer data in logs.
Always confirm the current webhook configuration and verification requirements in Shiprocket's documentation.
Step 9: Test Before Going Live
Before deploying your integration, test the complete workflow.
- Verify authentication and token handling.
- Test valid and invalid order payloads.
- Check courier serviceability and shipment creation.
- Test label generation and tracking.
- Handle API errors, timeouts, and rate limits.
- Confirm that duplicate requests do not create unwanted shipments.
- Protect customer information and API credentials.
Also consider adding structured logging, monitoring, retry policies, and automated tests for critical shipping operations.
Benefits of Shiprocket API Integration
Integrating shipping functionality into an e-commerce website can help businesses:
Automate shipping workflows: Reduce repetitive manual work when processing orders.
Improve order visibility: Make shipment information easier to access for customers and support teams.
Reduce operational overhead: Manage key shipping operations from a central application.
Build a better customer experience: Provide a more consistent checkout, dispatch, and tracking journey.
Conclusion
Integrating Shiprocket into an e-commerce website can simplify important shipping workflows, from order processing to delivery tracking.
A React.js frontend and Node.js backend provide a practical architecture for this integration. By keeping credentials secure, validating order data, handling API failures, and following the latest Shiprocket documentation, developers can build a more reliable shipping experience.
At Scode Software Solutions, we work on web, mobile, cloud, and AI-based software solutions to help businesses streamline operations and build practical digital products.
If you're planning an e-commerce application or need a custom shipping integration, a well-designed API workflow can be a valuable step toward improving operational efficiency.
Top comments (0)