Skip to content

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
└── .dockerignore

Creating the Dockerfile

Create a Dockerfile in the root of your repository:

FROM node:18-alpine
WORKDIR /app
# Install dependencies
RUN npm install -g npm@latest
RUN npm install -g @medusajs/medusa-cli
# Create a new Medusa project
RUN npx create-medusa-app@latest --skip-db --directory .
# Copy custom configuration
COPY medusa-config.js ./medusa-config.js
# Install additional plugins as needed
# RUN npm install medusa-plugin-stripe
# Build the admin dashboard
RUN npm run build:admin
# Expose the API port
EXPOSE 9000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f http://localhost:9000/health || exit 1
# Start Medusa
CMD ["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

VariableRequiredDefaultDescription
DATABASE_URLYes-PostgreSQL connection string
REDIS_URLYes-Redis connection string
JWT_SECRETYes-Secret for JWT token signing
COOKIE_SECRETYes-Secret for cookie signing
ADMIN_CORSNolocalhostAllowed origins for admin dashboard
STORE_CORSNolocalhostAllowed origins for storefront
NODE_ENVNodevelopmentEnvironment mode

Deploying on Klutch.sh

    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:

    Terminal window
    openssl rand -hex 32 # JWT_SECRET
    openssl rand -hex 32 # COOKIE_SECRET

    Push Your Repository to GitHub

    Initialize your repository and push to GitHub:

    Terminal window
    git init
    git add Dockerfile medusa-config.js .dockerignore README.md
    git commit -m "Initial MedusaJS deployment configuration"
    git remote add origin https://github.com/yourusername/medusajs-deploy.git
    git push -u origin main

    Create 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:

    • Select HTTP as the traffic type
    • Set the internal port to 9000

    Set Environment Variables

    Add the following environment variables:

    VariableValue
    DATABASE_URLYour PostgreSQL connection string
    REDIS_URLYour Redis connection string
    JWT_SECRETYour generated JWT secret
    COOKIE_SECRETYour generated cookie secret
    NODE_ENVproduction
    ADMIN_CORSYour admin dashboard URL
    STORE_CORSYour storefront URL

    Attach Persistent Volumes

    Add the following volumes:

    Mount PathRecommended SizePurpose
    /app/uploads10 GBProduct images and assets

    Deploy Your Application

    Click Deploy to start the build process. Klutch.sh will:

    • Detect your Dockerfile automatically
    • Build the container image
    • Run database migrations
    • Start the MedusaJS server
    • Provision an HTTPS certificate

    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:

  1. Access your container’s shell
  2. Run: npx medusa migrations run

Creating an Admin User

Create your first admin user:

Terminal window
npx medusa user -e admin@example.com -p your-password

Seeding Data

Optionally seed sample data:

Terminal window
npm run seed

Admin 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:

  1. Go to Products
  2. Click Add Product
  3. Enter product details, variants, and pricing
  4. Upload product images
  5. Publish the product

Setting Up Regions

Configure sales regions:

  1. Go to Settings > Regions
  2. Add regions for your target markets
  3. Configure currency, tax rates, and shipping options

Managing Orders

Track and fulfill orders:

  1. View incoming orders in Orders
  2. Process payments and fulfillments
  3. Handle returns and exchanges

API Integration

Store API

The Store API powers your customer-facing storefront:

// Example: Fetch products
const 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 request
const response = await fetch('https://your-api.klutch.sh/admin/products', {
headers: {
'Authorization': `Bearer ${adminToken}`
}
});

Payment Integration

Adding Stripe

Install and configure Stripe:

  1. Add to your Dockerfile: RUN npm install medusa-payment-stripe
  2. Configure in medusa-config.js
  3. Add Stripe API keys to environment variables

Payment Flow

  1. Customer adds items to cart
  2. Customer enters shipping details
  3. Payment session created via API
  4. Customer completes payment
  5. 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:

  1. Authenticate with the API
  2. Fetch products and collections
  3. Manage customer sessions
  4. 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

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.