Configure Medusa Backend

In this document, you’ll learn how to create a file service in the Medusa application and the methods you must implement in it.

The configurations for your Medusa application are in medusa-config.ts located in the root of your Medusa project. The configurations include configurations for database, modules, and more.

medusa-config.ts exports the value returned by the defineConfig utility function imported from @medusajs/framework/utils.

defineConfig accepts as a parameter an object with the following properties:

  • projectConfig (required): An object that holds general configurations related to the Medusa application, such as database or CORS configurations.
  • admin: An object that holds admin-related configurations.
  • modules: An object that configures the Medusa application's modules.
  • featureFlags: An object that enables or disables features guarded by a feature flag.

For example:

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    // ...4  },5  admin: {6    // ...7  },8  modules: {9    // ...10  },11  featureFlags: {12    // ...13  }14})

Environment Variables#

It's highly recommended to store the values of configurations in environment variables, then reference them within medusa-config.ts.

During development, you can set your environment variables in the .env file at the root of your Medusa application project. In production, setting the environment variables depends on the hosting provider.


projectConfig#

This property holds essential configurations related to the Medusa application, such as database and CORS configurations.

databaseName#

The name of the database to connect to. If the name is specified in databaseUrl, then you don't have to use this configuration.

Make sure to create the PostgreSQL database before using it. You can check how to create a database in PostgreSQL's documentation.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    databaseName: process.env.DATABASE_NAME ||4      "medusa-store",5    // ...6  },7  // ...8})

databaseUrl#

The PostgreSQL connection URL of the database, which is of the following format:

Terminal
postgres://[user][:password]@[host][:port]/[dbname]

Where:

  • [user]: (required) your PostgreSQL username. If not specified, the system's username is used by default. The database user that you use must have create privileges. If you're using the postgres superuser, then it should have these privileges by default. Otherwise, make sure to grant your user create privileges. You can learn how to do that in PostgreSQL's documentation.
  • [:password]: an optional password for the user. When provided, make sure to put : before the password.
  • [host]: (required) your PostgreSQL host. When run locally, it should be localhost.
  • [:port]: an optional port that the PostgreSQL server is listening on. By default, it's 5432. When provided, make sure to put : before the port.
  • [dbname]: (required) the name of the database.

You can learn more about the connection URL format in PostgreSQL’s documentation.

Example

For example, set the following database URL in your environment variables:

Terminal
DATABASE_URL=postgres://postgres@localhost/medusa-store

Then, use the value in medusa-config.ts:

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    databaseUrl: process.env.DATABASE_URL,4    // ...5  },6  // ...7})

databaseSchema#

The database schema to connect to. This is not required to provide if you’re using the default schema, which is public.

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    databaseSchema: process.env.DATABASE_SCHEMA ||4      "custom",5    // ...6  },7  // ...8})

databaseLogging#

This configuration specifies whether database messages should be logged.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    databaseLogging: false4    // ...5  },6  // ...7})

databaseDriverOptions#

This configuration is used to pass additional options to the database connection. You can pass any configuration. For example, pass the ssl property that enables support for TLS/SSL connections.

This is useful for production databases, which can be supported by setting the rejectUnauthorized attribute of ssl object to false. During development, it’s recommended not to pass this option.

NoteMake sure to add to the end of the database URL ?ssl_mode=disable as well when disabling rejectUnauthorized .

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    databaseDriverOptions: process.env.NODE_ENV !== "development" ?4      { ssl: { rejectUnauthorized: false } } : {}5    // ...6  },7  // ...8})

Properties

connectionobjectOptional

redisUrl#

This configuration specifies the connection URL to Redis to store the Medusa server's session.

NoteYou must first have Redis installed. You can refer to Redis's installation guide .

The Redis connection URL has the following format:

Terminal
redis[s]://[[username][:password]@][host][:port][/db-number]

For a local Redis installation, the connection URL should be redis://localhost:6379 unless you’ve made any changes to the Redis configuration during installation.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    redisUrl: process.env.REDIS_URL ||4      "redis://localhost:6379",5    // ...6  },7  // ...8})

redisPrefix#

This configuration defines a prefix on all keys stored in Redis for the Medusa server's session. The default value is sess:.

If this configuration option is provided, it is prepended to sess:.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    redisPrefix: process.env.REDIS_URL || "medusa:",4    // ...5  },6  // ...7})

redisOptions#

This configuration defines options to pass ioredis for the Redis connection used to store the Medusa server's session. Refer to ioredis’s RedisOptions documentation for the list of available options.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    redisOptions: {4      connectionName: process.env.REDIS_CONNECTION_NAME ||5        "medusa",6    }7    // ...8  },9  // ...10})

sessionOptions#

This configuration defines additional options to pass to express-session, which is used to store the Medusa server's session.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    sessionOptions: {4      name: process.env.SESSION_NAME || "custom",5    }6    // ...7  },8  // ...9})

Properties

namestringOptional
The name of the session ID cookie to set in the response (and read from in the request). The default value is connect.sid. Refer to express-session’s documentation for more details.
resavebooleanOptional
Whether the session should be saved back to the session store, even if the session was never modified during the request. The default value is true. Refer to express-session’s documentation for more details.
rollingbooleanOptional
Whether the session identifier cookie should be force-set on every response. The default value is false. Refer to express-session’s documentation for more details.
saveUninitializedbooleanOptional
Whether a session that is "uninitialized" is forced to be saved to the store. The default value is true. Refer to express-session’s documentation for more details.
secretstringOptional
The secret to sign the session ID cookie. By default, the value of http.cookieSecret is used. Refer to express-session’s documentation for details.
ttlnumberOptional
Used when calculating the Expires Set-Cookie attribute of cookies. By default, its value is 10 * 60 * 60 * 1000. Refer to express-session’s documentation for details.

workerMode#

Configure the application's worker mode.

Workers are processes running separately from the main application. They're useful for executing long-running or resource-heavy tasks in the background, such as importing products.

With a worker, these tasks are offloaded to a separate process. So, they won't affect the performance of the main application.

Diagram showcasing how the server and worker work together

Medusa has three runtime modes:

  • Use shared to run the application in a single process.
  • Use worker to run the a worker process only.
  • Use server to run the application server only.

In production, it's recommended to deploy two instances:

  1. One having the workerMode configuration set to server.
  2. Another having the workerMode configuration set to worker.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    workerMode: process.env.WORKER_MODE || "shared"4    // ...5  },6  // ...7})

http#

This property configures the application's http-specific settings.

Example

medusa-config.ts
1module.exports = defineConfig({2  projectConfig: {3    http: {4      cookieSecret: "supersecret",5      compression: {6        // ...7      }8    }9    // ...10  },11  // ...12})

Properties

authCorsstring
The Medusa application's API Routes are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s API Routes. cors is a string used to specify the accepted URLs or patterns for API Routes starting with /auth. It can either be one accepted origin, or a comma-separated list of accepted origins. Every origin in that list must either be:
  1. A URL. For example, http://localhost:7001. The URL must not end with a backslash;
  2. Or a regular expression pattern that can match more than one origin. For example, .example.com. The regex pattern that Medusa tests for is ^([/~@;%#'])(.*?)\1([gimsuy]*)$.
storeCorsstring
The Medusa application's API Routes are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s API Routes. store_cors is a string used to specify the accepted URLs or patterns for store API Routes. It can either be one accepted origin, or a comma-separated list of accepted origins. Every origin in that list must either be:
  1. A URL. For example, http://localhost:8000. The URL must not end with a backslash;
  2. Or a regular expression pattern that can match more than one origin. For example, .example.com. The regex pattern that the backend tests for is ^([/~@;%#'])(.*?)\1([gimsuy]*)$.
adminCorsstring
The Medusa application's API Routes are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s API Routes. admin_cors is a string used to specify the accepted URLs or patterns for admin API Routes. It can either be one accepted origin, or a comma-separated list of accepted origins. Every origin in that list must either be:
  1. A URL. For example, http://localhost:7001. The URL must not end with a backslash;
  2. Or a regular expression pattern that can match more than one origin. For example, .example.com. The regex pattern that the backend tests for is ^([/~@;%#'])(.*?)\1([gimsuy]*)$.
jwtSecretstringOptional
A random string used to create authentication tokens in the http layer. Although this configuration option is not required, it’s highly recommended to set it for better security. In a development environment, if this option is not set the default secret is supersecret. However, in production, if this configuration is not set, an error is thrown and the application crashes.
jwtExpiresInstringOptional
The expiration time for the JWT token. Its format is based off the ms package. If not provided, the default value is 24h.
cookieSecretstringOptional
A random string used to create cookie tokens in the http layer. Although this configuration option is not required, it’s highly recommended to set it for better security. In a development environment, if this option is not set, the default secret is supersecret. However, in production, if this configuration is not set, an error is thrown and the application crashes.
compressionHttpCompressionOptionsOptional
Configure HTTP compression from the application layer. If you have access to the HTTP server, the recommended approach would be to enable it there. However, some platforms don't offer access to the HTTP layer and in those cases, this is a good alternative. If you enable HTTP compression and you want to disable it for specific API Routes, you can pass in the request header "x-no-compression": true. Learn more in the API Reference.
authMethodsPerActorRecord<string, string[]>Optional
This configuration specifies the supported authentication providers per actor type (such as user, customer, or any custom actors). For example, you only want to allow SSO logins for users, while you want to allow email/password logins for customers to the storefront. authMethodsPerActor is a a map where the actor type (eg. 'user') is the key, and the value is an array of supported auth provider IDs.
restrictedFieldsobjectOptional
Specifies the fields that can't be selected in the response unless specified in the allowed query config. This is useful to restrict sensitive fields from being exposed in the API.

admin#

This property holds configurations for the Medusa Admin dashboard.

Example#

medusa-config.ts
1module.exports = defineConfig({2  admin: {3    backendUrl: process.env.MEDUSA_BACKEND_URL ||4      "http://localhost:9000"5  },6  // ...7})

disable#

Whether to disable the admin dashboard. If set to true, the admin dashboard is disabled, in both development and production environments. The default value is false.

Example

Code
1title = "medusa-config.ts"2module.exports = defineConfig({3  admin: {4    disable: process.env.ADMIN_DISABLED === "true" || false,5  },6  // ...7})

path#

The path to the admin dashboard. The default value is /app.

The value cannot be one of the reserved paths:

  • /admin
  • /store
  • /auth
  • /
NoteWhen using Docker, make sure that the root path of the Docker image doesn't path the admin's path . For example, if the Docker image's root path is /app , change the value of the path configuration, as it's /app by default.

Example

medusa-config.ts
1module.exports = defineConfig({2  admin: {3    path: process.env.ADMIN_PATH || `/app`,4  },5  // ...6})

outDir#

The directory where the admin build is outputted when you run the build command. The default value is ./build.

Example

medusa-config.ts
1module.exports = defineConfig({2  admin: {3    outDir: process.env.ADMIN_BUILD_DIR || `./build`,4  },5  // ...6})

backendUrl#

The URL of your Medusa application. This is useful to set when you deploy the Medusa application.

Example

medusa-config.ts
1module.exports = defineConfig({2  admin: {3    backendUrl: process.env.MEDUSA_BACKEND_URL ||4      "http://localhost:9000"5  },6  // ...7})

vite#

Configure the Vite configuration for the admin dashboard. This function receives the default Vite configuration and returns the modified configuration. The default value is undefined.


modules#

This property holds all custom modules installed in your Medusa application.

NoteMedusa's commerce modules are configured by default, so only add them to this property if you're changing their configurations or adding providers to a module.

modules is an array of objects, each holding a module's registration configurations. Each object has the following properties:

  1. resolve: a string indicating the path to the module relative to src, or the module's NPM package name. For example, ./modules/my-module.
  2. options: (optional) an object indicating the options to pass to the module.

Example#

medusa-config.ts
1module.exports = defineConfig({2  modules: [3    {4      resolve: "./modules/hello"5    }6  ]7  // ...8})

featureFlags#

Some features in the Medusa application are guarded by a feature flag. This ensures constant shipping of new features while maintaining the engine’s stability.

You can enable a feature in your application by enabling its feature flag. Feature flags are enabled through either environment variables or through this configuration property exported in medusa-config.ts.

The featureFlags's value is an object. Its properties are the names of the feature flags, and their value is a boolean indicating whether the feature flag is enabled.

You can find available feature flags and their key name here.

Example#

medusa-config.ts
1module.exports = defineConfig({2  featureFlags: {3    analytics: true,4    // ...5  }6  // ...7})
NoteAfter enabling a feature flag, make sure to run migrations as it may require making changes to the database.
Was this page helpful?