Deploying MedusaJS
Introduction
MedusaJS is an open-source headless commerce platform built for developers who want complete control over their e-commerce stack. Unlike monolithic platforms, Medusa provides a modular architecture with a powerful Node.js backend, allowing you to build custom storefronts with any frontend technology while maintaining a robust, scalable backend.
Built with TypeScript and designed for extensibility, MedusaJS offers a rich plugin ecosystem, flexible API, and built-in features for products, orders, customers, discounts, and more. The platform is designed to scale from small startups to enterprise-level commerce operations.
Key highlights of MedusaJS:
- Headless Architecture: Decouple your frontend from the backend for maximum flexibility
- TypeScript First: Built with TypeScript for type safety and better developer experience
- Plugin System: Extend functionality with official and community plugins
- Multi-Region Support: Built-in support for multiple currencies, languages, and tax rates
- Flexible Fulfillment: Integrate with any shipping provider or custom fulfillment logic
- Payment Integrations: Support for Stripe, PayPal, and custom payment providers
- Admin Dashboard: Modern admin panel for managing your store
- API-First: Comprehensive REST and GraphQL APIs
- Self-Hosted: Complete control over your data and infrastructure
- 100% Open Source: MIT licensed with active community
This guide walks through deploying MedusaJS on Klutch.sh using Docker, configuring the backend with PostgreSQL and Redis, and setting up the admin dashboard.
Why Deploy MedusaJS on Klutch.sh
Deploying MedusaJS on Klutch.sh provides several advantages for headless commerce:
Simplified Deployment: Klutch.sh automatically detects your Dockerfile and builds MedusaJS without complex orchestration. Push to GitHub, and your commerce backend deploys automatically.
Persistent Storage: Attach persistent volumes for your database and uploaded assets. Your product catalog and orders survive container restarts.
HTTPS by Default: Klutch.sh provides automatic SSL certificates, ensuring secure transactions for your customers.
GitHub Integration: Connect your configuration repository directly from GitHub. Updates trigger automatic redeployments.
Scalable Resources: Allocate CPU and memory based on your store’s traffic and transaction volume.
Custom Domains: Assign a custom domain to your MedusaJS API for a professional, branded experience.
Always-On Availability: Your commerce backend remains accessible 24/7, ensuring customers can always shop.
Prerequisites
Before deploying MedusaJS on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your configuration
- Basic familiarity with Docker and Node.js
- A PostgreSQL database (can be deployed on Klutch.sh)
- A Redis instance (can be deployed on Klutch.sh)
- (Optional) A custom domain for your API
Architecture Overview
MedusaJS requires several components:
- Medusa Backend: The core Node.js application
- PostgreSQL: Primary database for products, orders, customers
- Redis: Session storage and event queue
- Admin Dashboard: Optional React-based admin interface
- Storefront: Your custom frontend (Next.js, Gatsby, etc.)
Preparing Your Repository
To deploy MedusaJS on Klutch.sh, create a GitHub repository containing your Dockerfile and configuration.
Repository Structure
medusajs-deploy/├── Dockerfile├── medusa-config.js├── README.md└── .dockerignoreCreating the Dockerfile
Create a Dockerfile in the root of your repository:
FROM node:18-alpine
WORKDIR /app
# Install dependenciesRUN npm install -g npm@latestRUN npm install -g @medusajs/medusa-cli
# Create a new Medusa projectRUN npx create-medusa-app@latest --skip-db --directory .
# Copy custom configurationCOPY medusa-config.js ./medusa-config.js
# Install additional plugins as needed# RUN npm install medusa-plugin-stripe
# Build the admin dashboardRUN npm run build:admin
# Expose the API portEXPOSE 9000
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD curl -f http://localhost:9000/health || exit 1
# Start MedusaCMD ["npm", "run", "start"]Creating the Configuration File
Create medusa-config.js:
const dotenv = require("dotenv");
let ENV_FILE_NAME = "";switch (process.env.NODE_ENV) { case "production": ENV_FILE_NAME = ".env.production"; break; default: ENV_FILE_NAME = ".env"; break;}
try { dotenv.config({ path: process.cwd() + "/" + ENV_FILE_NAME });} catch (e) {}
const ADMIN_CORS = process.env.ADMIN_CORS || "http://localhost:7000,http://localhost:7001";const STORE_CORS = process.env.STORE_CORS || "http://localhost:8000";const DATABASE_URL = process.env.DATABASE_URL;const REDIS_URL = process.env.REDIS_URL;
const plugins = [ `medusa-fulfillment-manual`, `medusa-payment-manual`, { resolve: `@medusajs/admin`, options: { autoRebuild: true, develop: { open: process.env.OPEN_BROWSER !== "false", }, }, },];
module.exports = { projectConfig: { redis_url: REDIS_URL, database_url: DATABASE_URL, database_type: "postgres", store_cors: STORE_CORS, admin_cors: ADMIN_CORS, }, plugins,};Environment Variables Reference
| Variable | Required | Default | Description |
|---|---|---|---|
DATABASE_URL | Yes | - | PostgreSQL connection string |
REDIS_URL | Yes | - | Redis connection string |
JWT_SECRET | Yes | - | Secret for JWT token signing |
COOKIE_SECRET | Yes | - | Secret for cookie signing |
ADMIN_CORS | No | localhost | Allowed origins for admin dashboard |
STORE_CORS | No | localhost | Allowed origins for storefront |
NODE_ENV | No | development | Environment mode |
Deploying on Klutch.sh
- Select HTTP as the traffic type
- Set the internal port to 9000
- Detect your Dockerfile automatically
- Build the container image
- Run database migrations
- Start the MedusaJS server
- Provision an HTTPS certificate
Set Up PostgreSQL
Deploy a PostgreSQL database on Klutch.sh or use an external provider. Note the connection URL.
Set Up Redis
Deploy a Redis instance on Klutch.sh or use an external provider. Note the connection URL.
Generate Secrets
Generate secure secrets for JWT and cookies:
openssl rand -hex 32 # JWT_SECRETopenssl rand -hex 32 # COOKIE_SECRETPush Your Repository to GitHub
Initialize your repository and push to GitHub:
git initgit add Dockerfile medusa-config.js .dockerignore README.mdgit commit -m "Initial MedusaJS deployment configuration"git remote add origin https://github.com/yourusername/medusajs-deploy.gitgit push -u origin mainCreate a New Project on Klutch.sh
Navigate to the Klutch.sh dashboard and create a new project. Give it a descriptive name like “medusajs” or “commerce-backend”.
Create a New App
Within your project, create a new app. Connect your GitHub account if you haven’t already, then select the repository containing your MedusaJS Dockerfile.
Configure HTTP Traffic
MedusaJS serves its API over HTTP. In the deployment settings:
Set Environment Variables
Add the following environment variables:
| Variable | Value |
|---|---|
DATABASE_URL | Your PostgreSQL connection string |
REDIS_URL | Your Redis connection string |
JWT_SECRET | Your generated JWT secret |
COOKIE_SECRET | Your generated cookie secret |
NODE_ENV | production |
ADMIN_CORS | Your admin dashboard URL |
STORE_CORS | Your storefront URL |
Attach Persistent Volumes
Add the following volumes:
| Mount Path | Recommended Size | Purpose |
|---|---|---|
/app/uploads | 10 GB | Product images and assets |
Deploy Your Application
Click Deploy to start the build process. Klutch.sh will:
Access MedusaJS
Once deployment completes, access your API at https://example-app.klutch.sh. The admin dashboard is available at https://example-app.klutch.sh/app.
Initial Setup
Running Migrations
If migrations didn’t run automatically:
- Access your container’s shell
- Run:
npx medusa migrations run
Creating an Admin User
Create your first admin user:
npx medusa user -e admin@example.com -p your-passwordSeeding Data
Optionally seed sample data:
npm run seedAdmin Dashboard
Accessing the Dashboard
Navigate to https://your-app.klutch.sh/app and log in with your admin credentials.
Managing Products
In the admin dashboard:
- Go to Products
- Click Add Product
- Enter product details, variants, and pricing
- Upload product images
- Publish the product
Setting Up Regions
Configure sales regions:
- Go to Settings > Regions
- Add regions for your target markets
- Configure currency, tax rates, and shipping options
Managing Orders
Track and fulfill orders:
- View incoming orders in Orders
- Process payments and fulfillments
- Handle returns and exchanges
API Integration
Store API
The Store API powers your customer-facing storefront:
// Example: Fetch productsconst response = await fetch('https://your-api.klutch.sh/store/products');const { products } = await response.json();Admin API
The Admin API is for managing your store:
// Example: Authenticated admin requestconst response = await fetch('https://your-api.klutch.sh/admin/products', { headers: { 'Authorization': `Bearer ${adminToken}` }});Payment Integration
Adding Stripe
Install and configure Stripe:
- Add to your Dockerfile:
RUN npm install medusa-payment-stripe - Configure in
medusa-config.js - Add Stripe API keys to environment variables
Payment Flow
- Customer adds items to cart
- Customer enters shipping details
- Payment session created via API
- Customer completes payment
- Order confirmed and fulfillment begins
Storefront Development
Official Starters
MedusaJS provides starter storefronts:
- Next.js Starter: Full-featured React storefront
- Gatsby Starter: Static site generation
- Nuxt Starter: Vue.js storefront
Custom Integration
Build your own storefront using the Store API:
- Authenticate with the API
- Fetch products and collections
- Manage customer sessions
- Process checkout and payments
Troubleshooting
Database Connection Failed
- Verify PostgreSQL connection string
- Check database credentials
- Ensure database allows external connections
Redis Connection Issues
- Verify Redis URL format
- Check Redis authentication
- Ensure Redis is accessible
Admin Dashboard Not Loading
- Check ADMIN_CORS settings
- Verify admin build completed
- Review browser console for errors
Additional Resources
- MedusaJS Official Website
- MedusaJS Documentation
- MedusaJS GitHub Repository
- MedusaJS Discord
- Klutch.sh Persistent Volumes
- Klutch.sh Deployments
Conclusion
Deploying MedusaJS on Klutch.sh gives you a powerful, open-source commerce backend that you fully control. The headless architecture allows you to build custom shopping experiences with any frontend technology while leveraging MedusaJS’s robust backend for products, orders, and payments.
With Klutch.sh’s automatic deployments, persistent storage, and scalable resources, you can focus on building your commerce experience rather than managing infrastructure. Whether you’re building a small boutique or a large-scale marketplace, MedusaJS on Klutch.sh provides the foundation for flexible, scalable e-commerce.