Files
medusa-store/www/apps/docs/content/plugins/other/ip-lookup.md
Shahed Nasser fa7c94b4cc docs: create docs workspace (#5174)
* docs: migrate ui docs to docs universe

* created yarn workspace

* added eslint and tsconfig configurations

* fix eslint configurations

* fixed eslint configurations

* shared tailwind configurations

* added shared ui package

* added more shared components

* migrating more components

* made details components shared

* move InlineCode component

* moved InputText

* moved Loading component

* Moved Modal component

* moved Select components

* Moved Tooltip component

* moved Search components

* moved ColorMode provider

* Moved Notification components and providers

* used icons package

* use UI colors in api-reference

* moved Navbar component

* used Navbar and Search in UI docs

* added Feedback to UI docs

* general enhancements

* fix color mode

* added copy colors file from ui-preset

* added features and enhancements to UI docs

* move Sidebar component and provider

* general fixes and preparations for deployment

* update docusaurus version

* adjusted versions

* fix output directory

* remove rootDirectory property

* fix yarn.lock

* moved code component

* added vale for all docs MD and MDX

* fix tests

* fix vale error

* fix deployment errors

* change ignore commands

* add output directory

* fix docs test

* general fixes

* content fixes

* fix announcement script

* added changeset

* fix vale checks

* added nofilter option

* fix vale error
2023-09-21 20:57:15 +03:00

4.0 KiB
Raw Blame History

addHowToData
addHowToData
true

IP Lookup (ipstack) Plugin

In this document, youll 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 to allow you to detect a customers 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 to learn how to do it.

ipstack Account

You need an ipstack account 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:

npm install medusa-plugin-ip-lookup

Then, add the following environment variable in .env:

IPSTACK_ACCESS_KEY=<YOUR_ACCESS_KEY>

Where <YOUR_ACCESS_KEY> is your ipstack accounts access key. Its 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:

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 wont 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 users location by their IP address. It has only one method lookupIp that accepts the IP address as a parameter, sends a request to ipstacks API, and returns the retrieved result.

For example, you can use the IpLookupService in a custom endpoint and return the users region:

:::tip

You can learn more about creating an endpoint here.

:::

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 users location. For example, you can use it on the Create Cart endpoint to ensure that the users correct region is attached to the cart.

For example, you can attach it to all /store routes to ensure the customers region is always detected:

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
}