docs: Adds guides for plugins and storefront starters (#840)

This commit is contained in:
Oliver Windall Juhl
2021-11-23 18:08:00 +01:00
committed by GitHub
parent dec205f38e
commit 1de0b28f38
20 changed files with 1271 additions and 2 deletions

View File

@@ -0,0 +1,77 @@
# Algolia
We recently launched our sophisticated [Medusa](https://github.com/medusajs/medusa) Search API. It allows you to add a blazingly fast product search to your ecommerce setup, improving the overall customer experience and your conversion rates.
From a developer perspective, the Search API unifies communication between Medusa and search engines thereby allowing you to switch between different engines in seconds with only a couple of lines of code. So far, Medusa has only supported product search using MeiliSearch, but we can now proudly present a plugin for Algolia - one of the giants.
The purpose of this article is to show you how to install and configure Algolia for your Medusa store. Additionally, we'll showcase the powerful Search API by guiding you through changing from one search engine to another.
**Installation**
Create an account on Algolia and grab your Application ID and Admin API Key from the settings panel.
![algolia-config](https://i.imgur.com/kR6lWhI.png)
In your Medusa project, install the plugin using your favourite package manager:
```jsx
yarn add medusa-plugin-algolia@canary
// or
npm install medusa-plugin-algolia@canary
```
In your `medusa-config.js` add the integration to the array of plugins with the following settings:
```jsx
const plugins = [
// ...other plugins
{
resolve: `medusa-plugin-algolia`,
options: {
application_id: "your-application-id",
admin_api_key: "your-admin-api-key",
settings: {
products: {
searchableAttributes: [
"title",
"description",
],
attributesToRetrieve: [
"id",
"title",
"description",
"handle",
"thumbnail",
"variants",
"variant_sku",
"options",
"collection_title",
"collection_handle",
"images",
],
},
},
},
},
];
```
In the above config, you've provided the id and key from Algolia alongside a couple of settings, that define the properties you can search for and the values you'll get in return.
And that's all! You've now enabled Algolia for your Medusa store engine. The plugin will make sure to synchronize products from Medusa to Algolia upon updating, deleting, or creating new ones. Now all you need to do is to restart your server.
**Usage**
This article will not go too much into depth about how the search functionality works under the hood when querying the API. We refer to the [previous article on MeiliSearch](https://www.medusa-commerce.com/post/meilisearch-and-medusa) if this is of your interest. In there, you will find a quick showcase using Postman as well as a thorough walkthrough of how you can display the results in your storefront using ReactJS (GatsbyJS).
Instead, to illustrate the power of our Search API and search engine plugins, we'll switch out a MeiliSearch plugin with our new Algolia plugin in a store with existing products. Upon restarting the server with the new configuration, your products will automatically be fed into Algolia and the search functionality in your frontend will remain unchanged.
![Imgur](https://i.imgur.com/rIgAh6T.gif)
**Next up**
As mentioned in our post on MeiliSearch, we'll soon publish an article with a thorough walkthrough of our Search API. Until then, you should consider adding blazingly fast product search with one of our plugins to allow for your commerce business to grow to the next level.
Many thanks to community member Rolwin for building the plugin. If you want to be part of the Medusa community, feel free to join us on our [Discord channel](https://discord.gg/F87eGuwkTp).

View File

@@ -0,0 +1,300 @@
# Contentful
## Introduction
In this guide we will go over how to set up a modern e-commerce store using [Gatsby](https://gatsby.com) as a front end, [Contentful](https://contentful.com) as a CMS system and Medusa as a store engine. The resulting e-commerce store will be blazingly fast, highly extendable and will provide the necessary foundation to grow and evolve your e-commerce stack as your business expands to new markets and develops new software requirements.
## Overview
After following the steps outlines in this series you will have:
- A Medusa store engine capable of managing products, processing orders, handling orders and integrating with all the tools in your e-commerce stack.
- A statically generated Gatsby storefront that is on brand and customizable from homepage to checkout flow.
- A headless CMS system that can be modified and extended to create the best customer experience.
You will make use of `medusa-plugin-contentful` which is a plugin to your Medusa store engine that syncronizes products and product variants between your Medusa engine and your Contentful space. This allows you to perform content enrichment in Contentful while keeping your core master data in Medusa, for a truly headless commerce setup.
Other concepts that will be covered in this series include:
- Gatsby plugins and [File System Route API](https://www.gatsbyjs.com/docs/reference/routing/file-system-route-api/)
- [Contentful Migrations](https://www.contentful.com/developers/docs/tutorials/cli/scripting-migrations/)
- Medusa payments, fulfillments and plugins
If you want to jump straight to the code for this series you can checkout:
- [`medusa-starter-contentful`](https://github.com/medusajs/medusa-starter-contentful)
- [`medusa-contentful-storefront`](https://github.com/medusajs/medusa-contentful-storefront)
## Prerequisites
> For a full guide to how to set up your development environment for Medusa please see [the tutorial](https://docs.medusa-commerce.com/tutorials/set-up-your-development-environment)
In order to get you started with your Gatsby, Contentful, Medusa store you must complete a couple of installations:
- Install the Medusa CLI
```
yarn global add @medusajs/medusa-cli
npm install -g @medusajs/medusa-cli
```
- Install the Gatsby CLI
```
yarn global add gatsby-cli
npm install -g gatsby-cli
```
- [Create a Contentful account](https://www.contentful.com/sign-up/)
- [Install Redis](https://redis.io/topics/quickstart)
```
brew install redis
brew services start redis
```
Medusa has support for SQLite and PostgreSQL and uses Redis for caching and queueing of asynchronous tasks. Redis is required for `medusa-plugin-contentful` to work correctly.
## Setting up your Medusa server
We will make use of `medusa new` to setup your local Medusa server.
```sh
medusa new medusa-contentful-store https://github.com/medusajs/medusa-starter-contentful
```
This command will setup a new directory at `medusa-contentful-store`, clone the `medusa-starter-contentful` into that directory and install the dependencies for the project.
### What's inside
You can now do `cd medusa-contentful-store` and open up your project in your text editor. Below is an overview of the directory structure and a walkthrough of what the different files do.
```
medusa-contentful-store
├── contentful-migrations
| ├── hero.js
| ├── index.js
| ├── link.js
| ├── navigation-item.js
| ├── navigation-menu.js
| ├── page.js
| ├── product-variant.js
| ├── product.js
| ├── region.js
| ├── tile-section.js
| └── tile.js
├── data
| ├── contentful-seed.json
| └── seed.json
├── src
| ├── api
| ├── loaders
| ├── services
| └── subscribers
├── .env
├── medusa-config.js
├── package.json
└── README.md
```
#### `package.json`
If you are familiar with Node you will probably notice that your Medusa store is simply a Node project. Looking inside the `package.json` file you will find that one of the packages that is installed in the project is the `@medusajs/medusa` package. This is the core Medusa package that comes prepacked with all the functionality necessary to do digital commerce - it is also this package that makes sure to register and use the plugins and custom functionality that are configured for your store.
#### `medusa-config.js`
Your plugins and store configuration is managed in the `medusa-config.js`, if you open up the file you will see that `medusa-plugin-contentful` is configured with options as shown below. Later we will be setting up your Contentful space so that we can add the necessary environment variables to your `.env` file.
```javascript
// medusa-config.js
// Contentful Variables
const CONTENTFUL_SPACE_ID = process.env.CONTENTFUL_SPACE_ID || "";
const CONTENTFUL_ACCESS_TOKEN = process.env.CONTENTFUL_ACCESS_TOKEN || "";
const CONTENTFUL_ENV = process.env.CONTENTFUL_ENV || "";
const plugins = [
...,
{
resolve: `medusa-plugin-contentful`,
options: {
space_id: CONTENTFUL_SPACE_ID,
access_token: CONTENTFUL_ACCESS_TOKEN,
environment: CONTENTFUL_ENV,
},
},
...
];
module.exports = {
projectConfig: {
redis_url: REDIS_URL,
database_database: "./medusa-db.sql",
database_type: "sqlite",
store_cors: STORE_CORS,
admin_cors: ADMIN_CORS,
},
plugins,
};
```
#### `/src`
In the `/src` directory there are 4 special subdirectories that are added for you already. These special directories can be used to add custom functionality to your store. Custom functionality can include custom endpoints (configured in `/api`), custom business logic (configured in `/services`), pub/sub-like subscriptions for asyncrhonous integration tasks (configured in `/subscribers`) and finally loader functions to be called when your Medusa server starts up (configured in `/loaders`). If you want to learn more about how to add custom functionality you can checkout [the tutorial](https://docs.medusa-commerce.com/tutorials/adding-custom-functionality).
#### `/data`
We will be using two seed scripts to kickstart your development, namely `yarn seed:contentful` and `yarn seed`. Data for these seed scripts are contained in the `/data` directory.
When the seed scripts have been executed you will have a Contentful space that holds all the data for your website; this includes content for Pages, Navigtion Menu, etc.
#### `/contentful-migrations`
This directory contains scripts that create content types in your Contentful space. Contentful allows you to customize your content types with fields that can be used to hold all sorts of data, this makes it possible to create advanced data structures that will later be used to lay out your website. Writing migration scripts to evolve your content types is a really powerful tool as you can use it in CI/CD pipelines and makes your projects much more portable.
The migrations included in this project will create the following content types:
- **Page**: Represents a page on your website. Each page has a title and can take any number of "Content Modules". Content Modules can be either of the type Hero or Tile Section.
- **Hero**: a component that can take a Title, CTA and a background image.
- **Tile**: a component that can be added to a Tile Section and renders a Title, CTA and an Image.
- **Tile Section**: a component that can hold a number of Tiles or Products. When used with a Product, the Tile Section will display the product thumbnail and it's title and will link to the product page.
- **Link**: a component that can link to an external or internal path; or, alternatively, hold a reference to a Page or Product entry. If used with Page or Product, the link path will be infered from the referenced entry.
- **Navigation Item**: an item to include in a Navigation Menu. Each navigation item has a title that can be displayed in a menu and a link that defines where the user will be navigated to when the item is clicked.
- **Product**: represents a product as syncronized from Medusa. A product's variants will be copied over as well.
- **Product Variant**: The variants of a product.
- **Region**: Represents an available region in Medusa.
## Creating a Contentful space
To create a new Contentful space log in to your Contentful account. If you already have a Contentful account with a Space configured you can click your organization name in the top left corner to reveal an overview of your organization's spaces. At the bottom of the spaces list you should click "Add space".
**Select "Community space" and "Web app only"**
In this guide we will be using a free space which gives you an incredibly strong foundation for creating on-brand customer experiences and advances shopping flows.
![](https://i.imgur.com/JOAG8uk.png)
**Add a name and select "Empty space"**
![](https://i.imgur.com/Yt8xxoX.png)
Once your space is set up you can go to your space home. We will now get the credentials needed for `medusa-plugin-contentful` to work.
Open your `.env` file in your text editor you should see:
```shell
# .env
JWT_SECRET=something
COOKIE_SECRET=something
STRIPE_API_KEY=
STRIPE_WEBHOOK_SECRET=
CONTENTFUL_SPACE_ID=
CONTENTFUL_ACCESS_TOKEN=
CONTENTFUL_ENV=
```
Your `CONTENTFUL_SPACE_ID` can be found by going to your space home and checking your browser's URL bar. The space id is the alphanumeric string following `https://app.contentful.com/spaces/`. Copy this string and paste it into your `.env` file.
To get your `CONTENFUL_ACCESS_TOKEN` go to your space home and click **Settings** > **API keys**
![](https://i.imgur.com/ZF2VQSo.png)
Then click **Content management tokens** and click **Generate personal token**. After giving your token a name you can copy it to your `.env`
![](https://i.imgur.com/hcuAeKd.png)
For `CONTENTFUL_ENVIRONMENT` add `master`.
You should now have a `.env` that looks like this:
```shell
# .env
JWT_SECRET=something
COOKIE_SECRET=something
STRIPE_API_KEY=
STRIPE_WEBHOOK_SECRET=
CONTENTFUL_SPACE_ID=****
CONTENTFUL_ACCESS_TOKEN=CFPAT-*******
CONTENTFUL_ENV=master
```
## Migrating and Seeding your Contentful space
Now that we have collected your credentials we are ready to migrate the Contentful space to add the content types we talked about earlier. To migrate the Contentful space open up your command line and `cd` into `medusa-contentful-store`.
You can now run:
```shell
yarn migrate:contentful
```
This script will run each of the migrations in the `contentful-migrations` directory. After it has completed navigate to your Contentful space and click "Content model" in the top navigation bar. You will see that the content types will be imported into your space. Feel free to familiarize yourself with the different types by clicking them and inspecting the different fields that they hold.
![](https://i.imgur.com/E4x43vX.png)
The next step is to seed the Contentful space with some data that can be used to display your ecommerce store's pages and navigation. To seed the database open up your command line and run:
```shell
yarn seed:contentful
```
In your Contentful space navigate to "Content" and you will be able to see the different entries in your space. You can filter the entries by type to, for example, only view Pages:
![](https://i.imgur.com/5s8NNLT.png)
You will notice that there are not any Products in your store yet and this is because we haven't created any products in your Medusa store.
To do this open your command line and run:
```shell
yarn seed
yarn start
```
This will seed your Medusa database, which will result in `medusa-plugin-contentful` synchronizing data to your Contentful space. Everytime you add or update a product the data will be copied into your Contentful space for further enrichment.
## Setting Featured Products
In Contentful navigate to "Content" and find the Page called "Home". We will now add some featured products to the home page.
- Click the "Home" entry and scroll down to the field called "Content modules"
![](https://i.imgur.com/ab50vOa.png)
- Click the Content module named "Featured Products" and click "Add content" in the "Tiles" field
![](https://i.imgur.com/5GACc0e.png)
- Click "Add existing content" as e will be adding the products that were copied over by Medusa
![](https://i.imgur.com/igFPzdr.png)
- Select Medusa Waterbottle and Medusa Shirt and click "Insert 2 entries"
Make sure that everything is published by hitting publish in the sidebar on the right-hand side.
## Setting up your Gatsby storefront
Now that we have your Medusa server running and your Contentful space seeded with some starter data it is time to add a presentational layer that can be used by customers to browse and purchase the items in your store.
We have already created the storefront and you can install and use it by simply running:
```
gatsby new medusa-contentful-storefront https://github.com/medusajs/medusa-contentful-storefront
```
Once `gatsby new` is complete you should rename the `.env.template` file to `.env` and add a Content Delivery token. Your content delivery token is different from the personal access token you generated earlier, so make sure that you are using the correct token when you paste it into your `.env`.
To get your token go to **Settings** > **API Keys** > **Add API key**. Now click save and copy the token specified in the field "Content Delivery API - access token".
After you have copied the token and your space ID to your `.env`, you can run `yarn start` which will start your Gatsby development server on port 8000.
You can now go to https://localhost:8000 to check out your new Medusa store.
![](https://i.imgur.com/8MHrA73.png)
## Summary
Using three powerful tools we have now set up a modern headless ecommerce store on our local development machine. This setup can scale with your business's needs and evolve to fit create amazing commerce expereiences that are unique and on brand. The steps we took in this guide were really simple and fast: first we created a Medusa server using the Medusa CLI, we then configured a Contentful space by running migrations and seed scripts. We also installed a Gatsby front end for our Medusa store using the Gatsby CLI.
## What's next
In the next part we will dig deeper into how Contentful can be used to create pages, enrich your products and structure your content. We will also take a look at the files in your Gatsby storefront.
Stay tuned!

View File

@@ -0,0 +1,2 @@
# Klarna (Documentation coming soon)
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-klarna)

View File

@@ -0,0 +1,155 @@
# MeiliSearch
### Introduction
Search functionality is one of the most useful and important features in e-commerce platforms. From increasing customer conversion rates to significantly improving the user experience, search engines can enable significant business growth. Medusa brings search functionality to your doorstep by leveraging some of the already existing search engines out there.
We have developed a plugin that will allow you to use the performant, open-source, and feature-rich search engine MeiliSearch.
MeiliSearch is a super-fast, open-source, search engine built in Rust. It comes with a wide range of features such as typo-tolerance, filtering, sorting, and [much more](https://docs.meilisearch.com/learn/what_is_meilisearch/features.html). MeiliSearch also provides a pleasant developer experience, as it is extremely intuitive and newcomer-friendly - so even if you're new to the search engine "ecosystem", you'll have a great time navigating through their documentation.
Through Medusa flexible plugin system, it is possible to enable search functionality into your medusa applications with minimum hassle by including our new plugin `medusa-plugin-meilisearch` to your `medusa-config.js` file.
### Installation
In case you don't have MeiliSearch installed locally on your environment yet, you can run the following:
```bash
# Install MeiliSearch
curl -L https://install.meilisearch.com | sh
# Launch MeiliSearch
./meilisearch
```
For other installation alternatives, you can head over to Meilisearch's [installation guide](https://docs.meilisearch.com/learn/getting_started/installation.html).
In order to add the plugin to your medusa project, you will need to first install the plugin using your favorite package manager:
```bash
# yarn
yarn add medusa-plugin-meilisearch
# npm
npm install medusa-plugin-meilisearch
```
Then in your `medusa-config.js` file, add the plugin to your `plugins` array. For this example, assumption is that you're leveraging MeiliSearch to perform searches on an index called `products`
```jsx
module.exports = {
// ...other options
plugins: [
// ...other plugins
{
resolve: `medusa-plugin-meilisearch`,
options: {
// config object passed when creating an instance of the MeiliSearch client
config: {
host: "http://127.0.0.1:7700",
apiKey: "your_master_key"
},
settings: {
// index name
products: {
// MeiliSearch's setting options to be set on a particular index
searchableAttributes: ["title", "description", "variant_sku"],
displayedAttributes: ["title", "description", "variant_sku"],
},
},
},
},
],
};
```
Et voilà! That's all it takes to make medusa and MeiliSearch work in great harmony. Please note that you can use any other setting from this [list](https://docs.meilisearch.com/reference/features/settings.html#settings) such as `filterableAttributes`, `sortableAttributes`, and `synonyms`. We are working on another blog post that will demonstrate how you can make use of these settings to build a great storefront experience, so stay tuned to that!
### Simple Usage
Medusa exposes an API layer that can serve as an abstraction over various search providers. We will now be interacting with one of the search routes parts of that layer, namely, the `POST /store/products/search` route. The route will enable you to test out the integration between Medusa and MeiliSearch. The endpoint takes a mandatory `q` property and a set of optional parameters which will be passed to MeiliSearch's `search()` method as a second argument. The list of the parameters which can be provided can be found in MeiliSearch's [docs](https://docs.meilisearch.com/reference/api/search.html#search-in-an-index-with-post-route).
Let's use Postman for this short demo to get some search results:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zu09kroufrux94y6d5rq.png)
We tried to perform a search query "creneck" to find all crewnecks in our store. Note how the explicit mistake of leaving a "w" out from "crewneck" still yields the correct results.
Postman is not the most exciting client to use to showcase this, so in the next section, there is a short guide on how you can use React and MeiliSearchh's ecosystem to build something that looks better than JSON.
### Highlighting and Pagination in a React Storefront
The Medusa + MeiliSearch integration opens up a lot of capabilities for creating a rich UX for your storefront. The plugin indexes all your products and listens to any updates made on them, so you can then leverage any client-side SDKs developed by the MeiliSearch team to build cool search experiences for storefronts. For example, MeiliSearch exposes a React [adapter](https://github.com/meilisearch/meilisearch-react/) that can be used with React InstantSearch (made by Algolia) which provides features such as highlighting, filtering, and pagination out of the box.
In order to leverage this functionality, you'll need to install the corresponding packages by running:
```bash
# npm
npm install react-instantsearch-dom @meilisearch/instant-meilisearch
# yarn
yarn add react-instantsearch-dom @meilisearch/instant-meilisearch
```
You can then use the MeiliSearch client in your react app:
```jsx
import React from 'react';
import {
InstantSearch,
Hits,
SearchBox,
Pagination,
Highlight,
} from "react-instantsearch-dom";
import { instantMeiliSearch } from '@meilisearch/instant-meilisearch';
const searchClient = instantMeiliSearch(
"http://127.0.0.1:7700",
"your_master_key"
);
const SearchPage = () => (
<InstantSearch
indexName="products"
searchClient={searchClient}
>
<SearchBox />
<Hits hitComponent={Hit} />
<Pagination />
</InstantSearch>
);
const Hit = ({ hit }) => {
return (
<div key={hit.id}>
<div className="hit-name">
<Highlight attribute="name" hit={hit} />
</div>
<img src={hit.image} align="left" alt={hit.name} />
<div className="hit-description">
<Snippet attribute="description" hit={hit} />
</div>
<div className="hit-info">price: {hit.price}</div>
<div className="hit-info">release date: {hit.releaseDate}</div>
</div>
)
}
```
If you want to play around with the various features provided by React InstantSearch you can read more on algolia's [documentation](https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/react/). You can also use MeiliSearch's react [demo](https://codesandbox.io/s/ms-react-is-sh9ud?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js) for a more interactive example.
### Demo: Palmes Storefront
By using the above libraries (React, `react-instantsearch-dom`, and `instant-meilisearch`) in addition to the medusa plugin, we have successfully integrated the MeiliSearch plugin for one of our customers: Palmes. Following is a short GIF demoing the functionality.
[Palmes Tennis Society.mp4](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e0b596ab-e146-4151-a8b0-42c94401761f/Palmes_Tennis_Society.mp4)
### Enhance your development experience with MeiliSearch's Web UI
For a quicker feedback loop on what's happening on your search engine, you can use MeiliSearch's helpful out-of-the-box web interface to run some searches and get live results. It comes with MeiliSearch when you first install it and requires 0 configuration. When integrating the MeiliSearch plugin to existing medusa projects, we also found it to be extremely helpful for debugging
<iframe src="https://player.vimeo.com/video/639184340?h=593662d9f6" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>
### More to come
As briefly mentioned before, we're preparing another blog post that dives a bit deeper into the Medusa Search API and provides a more in-depth walkthrough on how to build a feature-rich search experience that includes filtering, synonyms, stop-words, and more!

View File

@@ -0,0 +1,2 @@
# PayPal (Documentation coming soon)
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-paypal)

View File

@@ -0,0 +1,85 @@
# S3
In order to work with images in Medusa, you need a file service plugin responsible for hosting. Following this guide will allow you to upload images to AWS S3.
### Before you start
At this point, you should have an instance of our store engine running. If not, we have a [full guide](https://docs.medusa-commerce.com/tutorial/set-up-your-development-environment) for setting up your local environment.
### Set up up AWS
#### Create an S3 bucket
In the AWS console navigate to S3 and create a bucket for your images. Make sure to uncheck "Block _all_ public access".
Additionally, you need to add a policy to your bucket, that will allow public access to objects that are uploaded. Navigate to the permissions tab of your bucket and add the following policy:
```shell=
{
"Id": "Policy1397632521960",
"Statement": [
{
"Sid": "Stmt1397633323327",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*",
"Principal": {
"AWS": [
"*"
]
}
}
]
}
```
Be aware, that this will allow for anyone to acces your bucket. Avoid storing sensitive data.
#### Generate access keys
Navigate to the IAM section of your AWS console and perform the following steps:
- Add a new user with programmatic access
- Add the existing **AmazonS3FullAccess** policy to the user
- Submit the details
Upon successfull creation of the user, you are presented with an **Access key ID** and a **Secret access key**. Note both of them down for later use.
### Installation
First, install the plugin using your preferred package manager:
```
yarn add medusa-file-s3
```
Then configure your `medusa-config.js` to include the plugin alongside the required options:
```=javascript
{
resolve: `medusa-file-s3`,
options: {
s3_url: "https://s3-guide-test.s3.eu-west-1.amazonaws.com",
bucket: "test",
region: "eu-west-1"
access_key_id: "YOUR-ACCESS-KEY",
secret_access_key: "YOUR-SECRET-KEY",
},
},
```
In the above options, an `s3_url` is included. The url has the following format:
```shell=
https://[bucket].s3.[region].amazonaws.com
```
The two access keys in the options are the ones created in the previous section.
> Make sure to use an environment variable for the secret key in a live environment.
### Try it out
Finally, run your Medusa server alongside our admin system to try out your new file service. Upon editing or creating products, you can now upload thumbnails and images, that are stored in an AWS S3 bucket.

View File

@@ -0,0 +1,100 @@
# Segment
Modern e-commerce businesses have to integrate with a wide spectrum of tools from marketing and personalization to analytics and business intelligence. Integrations to these tools quickly become hard to maintain and new integrations become overly complex to implement putting a stretch on an e-commerce organization's resources.
The CDP (Customer Data Platform) [Segment](https://segment.com/) solves this problem by allowing users to instantly integrate with +100 tools through a single unified API.
Medusa has an official plugin `medusa-plugin-segment` that instantly gives you access to all Segment integrations and comes preconfigured with powerful server-side tracking
## Why Segment?
Segment is a powerful Customer Data Platform that allows users to collect, transform, send and archive their customer data.
Segment allows users to manage different tracking and marketing tools using one API and interface, making it very simple to try out and integrate with different services in your e-commerce stack.
Common integration use cases that can be implemented with Segment include:
- Mailchimp
- Klaviyo
- Google Analytics Enhanced E-commerce tracking
- Data warehousing for advanced data analytics and segmentation through services like Snowflake
## Adding Segment to your Medusa store
> Note: you should create a [Node.js source in Segment](https://segment.com/docs/connections/sources/catalog/libraries/server/node/quickstart/) in order to obtain the write key that will be provided in the plugin options.
>
Plugins in Medusa's ecosystem come as separate npm packages, that can be installed from the npm registry.
```bash
yarn add medusa-plugin-segment
```
After installation open `medusa-config.js` to configure the Segment plugin, by adding it to your project's plugin array and providing the options required by the plugin, namely the write key obtained from the Segment dashboard.
```jsx
{
resolve: `medusa-plugin-segment`,
options: {
write_key: SEGMENT_WRITE_KEY,
}
}
```
After the plugin has been configured you will get instant access to +100 services through the Segment dashboard. This allows you to try out new services for your e-commerce stack without having to make heavy integration investments.
## Default tracking
`medusa-plugin-segment` comes with prebuilt tracking for common flows for Orders, Returns, Swaps, and Claims. Where applicable the events follow the [Segment Ecommerce Spec](https://segment.com/docs/connections/spec/ecommerce/v2/).
Below is a list of some of the events that are tracked by default:
- Orders
- Order Completed
- Order Shipped
- Order Refunded ← Without returned products
- Order Cancelled
- Returns
- Order Refunded ← With returned products
- Swaps
- Swap Created
- Swap Confirmed
- Swap Shipped
- Claims
- Item Claimed
The default events serve as a good foundation for e-commerce tracking, allowing you to answer questions regarding product performance, return ratios, claim statistics, and more.
In many cases you will want to track other events that are specific to your store - this is also possible through the Segment plugin, as the plugin registers the `segmentService` in your Medusa project.
## Tracking custom events
Building from the custom functionality that can be guided by [the tutorial](https://docs.medusa-commerce.com/tutorial/adding-custom-functionality) in Medusa docs, imagine that you want to track all welcome opt-ins.
The `segmentService` exposes a `track` method that wraps [Segment's Track Spec](https://segment.com/docs/connections/spec/track/), allowing you to send events to the Segment from anywhere in your Medusa project.
For example, to add tracking of the opt-ins in the `POST /welcome/:cart_id` endpoint, you could add the following code:
```jsx
const segmentService = req.scope.resolve("segmentService")
segmentService.track({
event: "Welcome Opt-In Registered",
properties: {
cart_id,
optin
}
})
```
The above snippet would send an event to Segment for further processing. The event data could be used for:
- Segmentation of a mailing list in MailChimp or Klaviyo based on whether the customer opted in for welcomes
- Storage in the data warehouse for later analysis to answer questions like "Are customers who opt-in for welcomes more likely to become recurring customers?"
- Integration to Google Analytics's events
- etc.
## What's next?
This article covers the introduction to one of many Medusa plugins and an explanation of how you can enhance your e-commerce stack, which will help you to build a successful e-commerce project.
Not sure where to start? We are happy to help and talk to you at our [Discord](https://discord.gg/EA5pd3WG)!

View File

@@ -0,0 +1,2 @@
# SendGrid (Documentation coming soon)
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-sendgrid)

View File

@@ -0,0 +1,2 @@
# Slack (Documentation coming soon)
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-slack-notification)

View File

@@ -0,0 +1,48 @@
# Spaces
In order to work with images in Medusa, you need a file service plugin responsible for hosting. Following this guide will allow you to upload images to DigitalOcean Spaces.
### Before you start
At this point, you should have an instance of our store engine running. If not, we have a [full guide](https://docs.medusa-commerce.com/tutorial/set-up-your-development-environment) for setting up your local environment.
### Set up up DigitalOcean
#### Create a Space
Create an account on DigitalOcean and navigate to Spaces. Create a new Space with the default settings.
#### Generate access keys
Navigate to API in the left sidebar. Generate a new Spaces access key. This should provide you with an access key id and a secret key. Note them both down.
### Installation
First, install the plugin using your preferred package manager:
```
yarn add medusa-file-spaces
```
Then configure your `medusa-config.js` to include the plugin alongside the required options:
```=javascript
{
resolve: `medusa-file-spaces`,
options: {
spaces_url: "https://test.fra1.digitaloceanspaces.com",
bucket: "test",
endpoint: "fra1.digitaloceanspaces.com",
access_key_id: "YOUR-ACCESS-KEY",
secret_access_key: "YOUR-SECRET-KEY",
},
},
```
In the above options, a `spaces_url` is included. This can be found in your Space overview. The `bucket` should point to the name you gave your Space. The `endpoint` identifies the region in which you created the Space. And finally the two keys are the ones created in the previous section.
> Make sure to use an environment variable for the secret key in a live environment.
### Try it out!
Finally, run your Medusa server alongside our admin system to try out your new file service. Upon editing or creating products, you can now upload thumbnails and images, that are stored in DigitalOcean Spaces.

View File

@@ -0,0 +1,173 @@
# Strapi
Use [Medusa](https://github.com/medusajs/medusa) and [Strapi](https://github.com/strapi/strapi) to power your commerce setup for a full open-source headless solution. In recent years, it has become increasingly popular to go with a headless approach when building ecommerce, blogs, portfolios, and the likes. Among many benefits, you get improved performance, more customizability, and support to scale as your business grows.
A headless system is essentially a decoupling of presentational layers and backend. It cuts off the traditional proprietary frontend displaying your content (hence the name), and instead gives you Rest APIs, you can consume from whatever system, client, or service you would like.
Going with the headless approach when building your setup will provide you with a modular system with best-in-breed services within each specific area of your stack; CMS, ecommerce, etc. This is in contrast to how you would traditionally choose a monolithic platform that partly (or hardly) caters to all of your needs.
This article will guide you through setting up a headless ecommerce setup in which content is managed by [Strapi](http://strapi.io) and the ecommerce is powered by [Medusa](https://github.com/medusajs/medusa) - on a 100% open-source stack.
## Why Medusa, and why Strapi?
The bottleneck of headless ecommerce systems is most often the amount of resources it requires to both get started and to maintain. You need backend developers to handle your infrastructure and integrations and frontend developers to build the customer experience. This is one of the reasons many existing headless solutions target enterprise businesses. To allow for small to mid-sized businesses to enter the space, one must cater to the developer experience. If the onboarding, setup, and implementation process are all easy to approach, you no longer need a team of ten to build a scalable ecommerce setup.
Strapi and Medusa are two systems built primarily for developers and the combination of the two enables you to build an ecommerce store with a blazingly fast, content-rich frontend and a highly extendable backend.
Both projects are open-source, headless, and built with Node.js. They use a very similar architecture for plugins and customizations, that gives you the ability to extend your commerce and CMS to fit exactly your needs. Let's now dive into the installation and setup of the two.
## Installation
The following guide for setting up the plugin assumes, that you are familiar with both Strapi and Medusa. If this is not the case, visit the official [Medusa](https://docs.medusa-commerce.com/tutorial/set-up-your-development-environment) and [Strapi](https://strapi.io/documentation/developer-docs/latest/getting-started/introduction.html) documentation.
### Setting up Medusa
First, create a Medusa project using your favorite package manager. You can go about this in two ways:
**Use `npx`**
`npx create-medusa-app` will allow you to create a Medusa store engine, a storefront, and Medusa admin in a single command
```bash
# using npx
npx create-medusa-app
# using yarn
yarn create medusa-app
```
> When choosing `npx` you are shown different store engine options as part of the setup. For this Strapi tutorial, you should choose `medusa-starter-default`. Optionally, pick a storefront.
**Use `medusa-cli`**
`@medusajs/medusa-cli` is our Command Line Tool for creating the Medusa store engine (alongside many other powerful commands). Use it as such:
```bash
# using yarn
yarn global add @medusajs/medusa-cli
# using npm
npm install -g @medusajs/medusa-cli
# initialise a Medusa project
medusa new my-medusa-store
```
Medusa uses Redis for emitting events in the system, so ensure, that this is installed and running
```
$ redis-cli
127.0.0.1:6379> ping
PONG
```
And in `medusa-config.js` you should enable it. Your project config in the bottom of the file should look similar to this:
```bash
projectConfig: {
redis_url: REDIS_URL,
database_database: "./medusa-db.sql",
database_type: "sqlite",
store_cors: STORE_CORS,
admin_cors: ADMIN_CORS,
},
```
Additionally, add Strapi to your list of plugins:
```json
{
resolve: `medusa-plugin-strapi`,
options: {
strapi_medusa_user: 'medusa_user',
strapi_medusa_password: 'medusaPassword1',
strapi_url: '127.0.0.1',
strapi_port: '1337'
}
}
```
And finally, install the plugin using your package manager:
```bash
#using yarn
yarn add medusa-plugin-strapi
# using npm
npm install medusa-plugin-strapi
```
You've now successfully installed and configured your Medusa store engine. Seed it with data and start it up by running:
```bash
# using npm
npm run seed && npm start
# using yarn
yarn seed && yarn start
```
We'll now turn to the Strapi side of things.
### Setting up Strapi
Similar to how you installed Medusa, you can install Strapi using your favorite package manager. Use the `strapi-medusa-template` to create your project. The template is a custom Strapi implementation required for the two systems to work together.
```bash
# using npx
npx create-strapi-app strapi-medusa --template https://github.com/Deathwish98/strapi-medusa-template.git
# using yarn
yarn create strapi-app strapi-medusa --template https://github.com/Deathwish98/strapi-medusa-template.git
```
After running the command, you have a full Strapi project configured to synchronize with Medusa. Upon the initial start of the Strapi server, all the required models will be created. They will correlate with models from Medusa to allow for two-way synchronization.
> Note: The Strapi template starter uses SQLite as the default database. There is a known bug related to `knex.js` that comes from multiple write connections. Restarting the Strapi server should make the error disappear.
**Synchronization**
The power of using Strapi with Medusa comes from two-way synchronization. Strapi allows you to enrich your products with extra fields and data, such that you can perfect the customer experience. But for the products to appear in Strapi, you are required to create them in Medusa. For the commerce logic in your presentational layer to function properly, you need the Medusa IDs of products and variants. This is used for operations like adding to cart and going through the checkout flow.
When products are created in Medusa, the two-way communication ensures that data is kept consistent between the two systems. Though only some fields are synchronized and those are:
**Product**: title, subtitle, description, handle
**Variants**: title
**Region**: name
> Further down the road, the support for synchronizing more entities is expected to be introduced
**Using Postgres in Medusa (optional)**
For Postgres to function, you need to create a local database. One way of doing this would be to use your terminal:
```json
createdb medusa-store
```
Depending on what system you are on and how your local Postgres is configured, the above command might fail. In that case, please investigate the correct way to create a local database on your pc.
Navigate to your newly created Medusa project (`<project name>/backend` if you used `npx`). In `medusa-config.js`, ensure that you have Redis and Postgres enabled. The project configurations at the bottom of the file should look similar to this:
```bash
projectConfig: {
redis_url: REDIS_URL,
database_url: DATABASE_URL,
database_type: "postgres",
store_cors: STORE_CORS,
admin_cors: ADMIN_CORS,
},
```
> Note: the `DATABASE_URL` variable should use the Postgres database created in the previous step
## Summary and next steps
You are now provided with the toolbox for creating amazing digital commerce experiences on top of a highly extendable CMS system and ecommerce platform.
To quickly get started, see our starters for:
- [GatsbyJS](https://github.com/medusajs/gatsby-starter-medusa) (much more feature-rich V2 coming soon)
- [NextJS](https://github.com/medusajs/nextjs-starter-medusa)
A big thanks to community member Pawan Sharma ([Deathwish98](https://github.com/Deathwish98)) for leading the implementation of this integration with Strapi. If you want to be part of the Medusa community, feel free to join us on our [Discord channel](https://discord.gg/F87eGuwkTp).

View File

@@ -0,0 +1,3 @@
# Stripe (Documentation coming soon)
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-stripe)

View File

@@ -0,0 +1,44 @@
# Quickstart: Gatsby
**Create a new Gatsby project using the Medusa starter template**
```bash
gatsby new my-medusa-store https://github.com/medusajs/gatsby-starter-medusa
```
**Set up environment variables**
Navigate into your projects directory and get your environment variables ready:
```shell
mv .env.template .env.development
```
**Install dependencies**
Use your favourite package manager to install dependencies:
```shell
yarn
# or
npm install
```
**Start developing.**
Start up the local server:
```shell
yarn start
```
Your site is now running at http://localhost:8000!
Edit `src/pages/index.js` to see your site update in real-time!
**Learn more about Medusa**
- [Website](https://www.medusa-commerce.com/)
- [GitHub](https://github.com/medusajs)
- [Documentation](https://docs.medusa-commerce.com/)
**Learn more about Gatsby**
- [Documentation](https://www.gatsbyjs.com/docs/?utm_source=starter&utm_medium=readme&utm_campaign=minimal-starter)
- [Tutorials](https://www.gatsbyjs.com/tutorial/?utm_source=starter&utm_medium=readme&utm_campaign=minimal-starter)
- [Guides](https://www.gatsbyjs.com/tutorial/?utm_source=starter&utm_medium=readme&utm_campaign=minimal-starter)
- [API Reference](https://www.gatsbyjs.com/docs/api-reference/?utm_source=starter&utm_medium=readme&utm_campaign=minimal-starter)
- [Plugin Library](https://www.gatsbyjs.com/plugins?utm_source=starter&utm_medium=readme&utm_campaign=minimal-starter)
- [Cheat Sheet](https://www.gatsbyjs.com/docs/cheat-sheet/?utm_source=starter&utm_medium=readme&utm_campaign=minimal-starter)

View File

@@ -0,0 +1,39 @@
# Quickstart: Next.js
**Create a new Next.js project using the Medusa starter template**
```bash
npx create-next-app -e https://github.com/medusajs/nextjs-starter-medusa my-medusa-storefront
```
**Set up environment variables**
Navigate into your projects directory and get your environment variables ready:
```shell
mv .env.template .env.local
```
**Install dependencies**
Use your favourite package manager to install dependencies:
```shell
yarn
# or
npm install
```
**Start developing.**
Start up the local server:
```shell
yarn dev
```
Your site is now running at http://localhost:8000!
Edit `src/pages/index.js` to see your site update in real-time!
**Learn more about Medusa**
- [Website](https://www.medusa-commerce.com/)
- [GitHub](https://github.com/medusajs)
- [Documentation](https://docs.medusa-commerce.com/)
**Learn more about Next.js**
- [Documentation](https://nextjs.org/docs)

View File

@@ -0,0 +1,21 @@
# CORS issues
If you are experiencing connection issues when trying to access your Medusa instance from a storefront, it is most likely due to CORS issues.
You might see a log in your browser console, that looks like this:
![CORS error log](https://i.imgur.com/jnHK115.png)
In your `medusa-config.js` , you should ensure that you've configured your CORS settings correctly. By default, the Medusa starter run on port 9000, Medusa Admin on port 7000, and the storefront starters on port 8000.
The default configuration uses the following CORS settings:
```jsx
// CORS when consuming Medusa from admin
const ADMIN_CORS = process.env.ADMIN_CORS || "http://localhost:7000";
// CORS to avoid issues when consuming Medusa from a client
const STORE_CORS = process.env.STORE_CORS || "http://localhost:8000"
```
If you wish to run your storefront or Medusa admin on other ports, you should update the above settings accordinly.

View File

@@ -0,0 +1,29 @@
# Stripe not showing in checkout
You add payment providers to your Medusa instance by adding them as plugins in `medusa-config.js`:
```jsx
const plugins = [
...
// You can create a Stripe account via: https://stripe.com
{
resolve: `medusa-payment-stripe`,
options: {
api_key: STRIPE_API_KEY,
webhook_secret: STRIPE_WEBHOOK_SECRET,
},
},
...
];
```
And installing them through your favourite package manager:
```bash
yarn add medusa-payment-stripe
# or
npm install medusa-payment-stripe
```
Though, to be able to also show them as part of your checkout flow, you need to add them to your regions.
In Medusa Admin go to Settings -> Regions and select your newly added payment provider:
![](https://i.imgur.com/CfR9BCV.png)

View File

@@ -0,0 +1,23 @@
# Redis not emitting events
When you create a new Medusa project, Redis is disabled by default. Instead, we use a fake Redis server, that allows you to start your project, but holds no functionality.
To enable a real Redis server, you need to install and start it up on your PC. Install it directly from their [website](https://redis.io/download) or use Homebrew and run the following commands:
```bash
brew install redis
brew services start redis
```
Additonally, ensure that `redis_url` is not commented out in your project configuration in the bottom of your `medusa-config.js`.
```jsx
module.exports = {
projectConfig: {
redis_url: REDIS_URL, // <-- Enables a real Redis server
database_url: DATABASE_URL,
database_type: "postgres",
store_cors: STORE_CORS,
admin_cors: ADMIN_CORS,
},
plugins,
};
```

View File

@@ -0,0 +1,11 @@
# Signing in to Medusa Admin
If you've created a new Medusa project and seeded the database using our predefined script, the default credentials are:
```bash
admin@medusa-test.com // supersecret
```
Though, you can create your own users using our CLI:
```
medusa user -e some@email.com -p somepassword
```

View File

@@ -0,0 +1,34 @@
# Error 409 in checkout
To provide the most frictionless onboarding and quick start, we default to SQLite as database. SQLite runs on all PCs, which is why it allows you to get quickly started without installing Postgres. Though, it comes at the expense of important features, that are needed in a production environment.
Therefore, you might experience the following error when going through a checkout flow in our starters:
```
Error: Transaction already started for the given connection, commit current transaction before starting a new one.
```
This error occurs because SQLite does not allow for multiple write transactions at the same time. To resolve it, you need to use Postgres instead.
First install and start Postgres on your local machine. You can either [download it directly from their website](https://www.postgresql.org/download/) or use Homebrew:
```bash
brew install postgresql
brew services start postgresql
createdb
```
Then in your `medusa-config.js`, you should change the project config to use Postgres as database type:
```jsx
module.exports = {
projectConfig: {
redis_url: REDIS_URL,
// The following two lines will enable Postgres
database_url: DATABASE_URL,
database_type: "postgres",
store_cors: STORE_CORS,
admin_cors: ADMIN_CORS,
},
plugins,
};
```
> When changing from SQLite to Postgres, you should seed the database again using: `yarn seed`