Skip to content

Commit

Permalink
docs: added multi-region recipe (#4926)
Browse files Browse the repository at this point in the history
* docs: added a multi-region recipe

* added other category to plugins list

* fix eslint errors

* fix broken link

* add link

* fix sidebar link
  • Loading branch information
shahednasser authored Aug 31, 2023
1 parent f9c064f commit ddc882f
Show file tree
Hide file tree
Showing 6 changed files with 520 additions and 1 deletion.
5 changes: 5 additions & 0 deletions www/docs/content/plugins/other/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import DocCardList from '@theme/DocCardList';

# Other Plugins

<DocCardList />
143 changes: 143 additions & 0 deletions www/docs/content/plugins/other/ip-lookup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
---
addHowToData: true
---

# IP Lookup (ipstack) Plugin

In this document, you’ll learn how to install the IP Lookup plugin on your Medusa backend.

## Overview

Location detection in a commerce store is essential for multi-region support. Medusa provides an IP Lookup plugin that integrates the backend with [ipstack](https://ipstack.com/) to allow you to detect a customer’s location and, ultimately, their region.

This guide explains how you can install and use this plugin.

---

## Prerequisites

### Medusa Backend

Before you follow this guide, you must have a Medusa backend installed. If not, you can follow the [quickstart guide](../../create-medusa-app.mdx) to learn how to do it.

### ipstack Account

You need an [ipstack account](https://ipstack.com/) before using this plugin. You can create a free account with ipstack on their website.

---

## Install Plugin

In the root directory of your Medusa backend, run the following command to install the IP Lookup plugin:

```bash npm2yarn
npm install medusa-plugin-ip-lookup
```

Then, add the following environment variable in `.env`:

```bash
IPSTACK_ACCESS_KEY=<YOUR_ACCESS_KEY>
```

Where `<YOUR_ACCESS_KEY>` is your ipstack account’s access key. It’s available in your ipstack dashboard.

Finally, add the IP lookup plugin into the plugins array exported as part of the Medusa configuration in `medusa-config.js`:

```js title=medusa-config.js
const plugins = [
// other plugins...
{
resolve: `medusa-plugin-ip-lookup`,
options: {
access_token: process.env.IPSTACK_ACCESS_KEY,
},
},
]
```

---

## Test the Plugin

The plugin provides two resources: the `IpLookupService` and the `preCartCreation` middleware.

:::note

Due to how Express resolves the current IP when accessing your website from `localhost`, you won’t be able to test the plugin locally. You can either use tools like ngrok to expose the `9000` port to be accessed publicly, or you have to test it on a deployed backend.

:::

### IpLookupService

The `IpLookupService` can be used in other services, endpoints, or resources to get the user’s location by their IP address. It has only one method `lookupIp` that accepts the IP address as a parameter, sends a request to ipstack’s API, and returns the retrieved result.

For example, you can use the `IpLookupService` in a custom endpoint and return the user’s region:

:::tip

You can learn more about creating an endpoint [here](../../development/endpoints/create.mdx).

:::

```ts title=src/api/index.ts
import { Request, Response, Router } from "express"

export default (rootDirectory: string): Router | Router[] => {
const router = Router()
// ...
router.get(
"/store/customer-region",
async (req: Request, res: Response) => {
const ipLookupService = req.scope.resolve(
"ipLookupService"
)
const regionService = req.scope.resolve<RegionService>(
"regionService"
)

const ip = req.headers["x-forwarded-for"] ||
req.socket.remoteAddress

const { data } = await ipLookupService.lookupIp(ip)

if (!data.country_code) {
throw new Error ("Couldn't detect country code.")
}

const region = await regionService
.retrieveByCountryCode(data.country_code)

res.json({
region,
})
}
)
}
```

### preCartCreation

The `preCartCreation` middleware can be added as a middleware to any route to attach the region ID to that route based on the user’s location. For example, you can use it on the Create Cart endpoint to ensure that the user’s correct region is attached to the cart.

For example, you can attach it to all `/store` routes to ensure the customer’s region is always detected:

<!-- eslint-disable @typescript-eslint/no-var-requires -->

```ts title=src/api/index.ts
import { Router } from "express"

const { preCartCreation } = require(
"medusa-plugin-ip-lookup/api/medusa-middleware"
).default

export default (
rootDirectory: string
): Router | Router[] => {
const router = Router()
// ...
router.use("/store", preCartCreation)

return router
}
```
9 changes: 9 additions & 0 deletions www/docs/content/plugins/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ Interested in creating a plugin? Learn more in the [Create Plugin documentation]
description: 'Check out official File Service plugins.'
}
},
{
type: 'link',
href: '/plugins/other',
label: 'Other Plugins',
customProps: {
icon: Icons['squares-plus-solid'],
description: 'Check out other official plugins.'
}
},
]} />

<!-- vale docs.Acronyms = YES -->
26 changes: 25 additions & 1 deletion www/docs/content/recipes/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Follow this guide if you want to build a B2B/Wholesale store.
href: '/recipes/b2b',
label: 'Build B2B Store',
customProps: {
icon: Icons['credit-card-solid'],
icon: Icons['building-solid'],
description: 'Learn how you can build a B2B store in Medusa.'
}
}} />
Expand All @@ -87,6 +87,30 @@ Follow this guide if you want to build a B2B/Wholesale store.

---

## Recipe: Build Multi-Region Store

Learn how you can build a multi-region store with Medusa.

<DocCard item={{
type: 'link',
href: '/recipes/multi-region',
label: 'Build Multi-Region Store',
customProps: {
icon: Icons['globe-europe-solid'],
description: 'Learn how you can build a multi-region store in Medusa.'
}
}} />

<Feedback
event="survey_use_cases"
question="Did your find your use case?"
positiveQuestion="Is there anything that should improved?"
negativeQuestion="What was your use case?"
showLongForm={false}
/>

---

<!-- vale docs.HeadingPunctuation = NO -->

## Can't find your path?
Expand Down
Loading

2 comments on commit ddc882f

@vercel
Copy link

@vercel vercel bot commented on ddc882f Aug 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

api-reference – ./www/api-reference

api-reference-git-develop-medusajs.vercel.app
api-reference-medusajs.vercel.app
api-reference-delta.vercel.app
docs.medusajs.com

@vercel
Copy link

@vercel vercel bot commented on ddc882f Aug 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

medusa-docs – ./www/docs

medusa-docs-medusajs.vercel.app
medusa-docs.vercel.app
medusa-docs-git-develop-medusajs.vercel.app

Please sign in to comment.