Skip to content

Instantly share code, notes, and snippets.

@gohlance
Created November 3, 2024 09:25
Show Gist options
  • Save gohlance/2f2df4324aa9d865e411500741fafe51 to your computer and use it in GitHub Desktop.
Save gohlance/2f2df4324aa9d865e411500741fafe51 to your computer and use it in GitHub Desktop.
Setup Medusa ip lookup
github link : https://github.com/luluhoc/medusa-plugin-ip-lookup-maxmind-updated
Download the geolite db
In backend/medusa-config.ts
{
resolve: `medusa-plugin-ip-lookup-maxmind-geoip2`,
/** @type {import('medusa-plugin-ip-lookup-maxmind-geoip2').PluginOptions} */
options: {
maxmind_db_path: "data/geodata/GeoLite2-Country.mmdb",
route_enabled: true, // This route is under store so it's public
}
}
*data/geodata is the folder and you need to specifiy the mmdb name.
In storefront/middleware.ts
/**
* Fetches regions from Medusa and sets the region cookie.
* @param request
* @param response
*/
async function getCountryCode(
request: NextRequest,
regionMap: Map<string, Region | number>
) {
try {
let countryCode
const maxmindDBCountryCode = await fetch(`${BACKEND_URL}/store/ip-lookup`)
const data = await maxmindDBCountryCode.json();
const urlCountryCode = request.nextUrl.pathname.split("/")[1]?.toLowerCase()
if (data.country_code && regionMap.has(data.country_code)){
countryCode = data.country_code;
}if (urlCountryCode && regionMap.has(urlCountryCode)) {
countryCode = urlCountryCode
} else if (regionMap.has(DEFAULT_REGION)) {
countryCode = DEFAULT_REGION
} else if (regionMap.keys().next().value) {
countryCode = regionMap.keys().next().value
}
/**
if (urlCountryCode && regionMap.has(urlCountryCode)) {
countryCode = urlCountryCode
} else if (regionMap.has(DEFAULT_REGION)) {
countryCode = DEFAULT_REGION
} else if (regionMap.keys().next().value) {
countryCode = regionMap.keys().next().value
}
*/
return countryCode
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error(
"Middleware.ts: Error getting the country code. Did you set up regions in your Medusa Admin and define a NEXT_PUBLIC_MEDUSA_BACKEND_URL environment variable?"
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment