1 export const metadata = {
2 title: `Remove Country Code Prefix in Next.js Starter Storefront`,
3 }
4
5 # {metadata.title}
6
7 In this guide, you'll learn how to remove the country code prefix from the URLs in the Next.js Starter Storefront.
8
9 ## Overview
10
11 By default, the Next.js Starter Storefront includes a country code prefix in URLs that indicates the customer's selected country. For example, if a customer selects the United States, the URL includes the prefix `/us`.
12
13 You may want to remove the country code prefix for a cleaner URL structure or to handle country selection differently.
14
15 ### Summary
16
17 To remove the country code prefix from URLs, you need an alternative way to store and access the country code. The country code is necessary to determine the associated region, which is used for carts, prices, and available payment methods.
18
19 This guide shows you how to:
20
21 1. Store and manage the country code using cookies.
22 2. Update the middleware to handle country code retrieval from cookies.
23 3. Restructure the routes to remove the country code prefix.
24 4. Update components and pages to use the country code from cookies.
25
26 ---
27
28 ## 1. Add Country Code Cookie Utilities
29
30 You'll start by adding utility functions to manage the country code cookie.
31
32 In `src/lib/data/cookies.ts`, add the following at the end of the file:
33
34 ```ts title="src/lib/data/cookies.ts"
35 export const COUNTRY_CODE_COOKIE_NAME = "_medusa_country_code"
36
37 /**
38 * Gets the current country code from cookies
39 */
40 export const getCountryCode = async (): Promise<string | null> => {
41 try {
42 const cookies = await nextCookies()
43 return cookies.get(COUNTRY_CODE_COOKIE_NAME)?.value ?? null
44 } catch {
45 return null
46 }
47 }
48
49 /**
50 * Sets the country code cookie
51 */
52 export const setCountryCode = async (countryCode: string) => {
53 const cookies = await nextCookies()
54 cookies.set(COUNTRY_CODE_COOKIE_NAME, countryCode, {
55 maxAge: 60 * 60 * 24 * 365, // 1 year
56 httpOnly: false, // Allow client-side access
57 sameSite: "strict",
58 secure: process.env.NODE_ENV === "production",
59 })
60 }
61 ```
62
63 You add two utility functions:
64
65 1. `getCountryCode`: Retrieves the country code from cookies.
66 2. `setCountryCode`: Sets the country code cookie with appropriate options.
67
68 The country code is stored in the `_medusa_country_code` cookie, following the Next.js Starter Storefront's naming conventions.
69
70 ---
71
72 ## 2. Update Middleware to Remove Country Code from URL
73
74 The Next.js Starter Storefront uses middleware at `src/middleware.ts` to handle country code prefixes in URLs, among other functionalities.
75
76 You'll update the middleware to remove the country code prefix from URLs and store it in a cookie instead. This ensures that all requests are handled correctly without requiring a country code in the URL.
77
78 In `src/middleware.ts`, add the following import at the top of the file:
79
80 ```ts title="src/middleware.ts"
81 import { COUNTRY_CODE_COOKIE_NAME } from "@lib/data/cookies"
82 ```
83
84 Then, update the `getCountryCode` function in the middleware to the following:
85
86 ```ts title="src/middleware.ts"
87 /**
88 * Determines the country code from cookie or headers.
89 * @param request
90 * @param regionMap
91 */
92 async function getCountryCode(
93 request: NextRequest,
94 regionMap: Map<string, HttpTypes.StoreRegion | number>
95 ) {
96 try {
97 // First, check if country code is already in cookie
98 const cookieCountryCode = request.cookies.get(COUNTRY_CODE_COOKIE_NAME)?.value?.toLowerCase()
99 if (cookieCountryCode && regionMap.has(cookieCountryCode)) {
100 return cookieCountryCode
101 }
102
103 // Check Vercel IP country header
104 const vercelCountryCode = request.headers
105 .get("x-vercel-ip-country")
106 ?.toLowerCase()
107 if (vercelCountryCode && regionMap.has(vercelCountryCode)) {
108 return vercelCountryCode
109 }
110
111 // Fall back to default region
112 if (regionMap.has(DEFAULT_REGION)) {
113 return DEFAULT_REGION
114 }
115
116 // Last resort: use first available region
117 if (regionMap.keys().next().value) {
118 return regionMap.keys().next().value
119 }
120
121 return null
122 } catch (error) {
123 if (process.env.NODE_ENV === "development") {
124 console.error(
125 "Middleware.ts: Error getting the country code. Did you set up regions in your Medusa Admin and define a MEDUSA_BACKEND_URL environment variable? Note that the variable is no longer named NEXT_PUBLIC_MEDUSA_BACKEND_URL."
126 )
127 }
128 return null
129 }
130 }
131 ```
132
133 In this updated function, you:
134
135 1. Check if the country code is already stored in the cookie.
136 2. Fall back to the Vercel IP country header if not found in the cookie.
137 3. Use the default region or the first available region if necessary.
138
139 Finally, update the `middleware` function to the following:
140
141 ```ts title="src/middleware.ts"
142 /**
143 * Middleware to handle region selection and country code cookie management.
144 */
145 export async function middleware(request: NextRequest) {
146 // Check if the url is a static asset
147 if (request.nextUrl.pathname.includes(".")) {
148 return NextResponse.next()
149 }
150
151 const cacheIdCookie = request.cookies.get("_medusa_cache_id")
152 const cacheId = cacheIdCookie?.value || crypto.randomUUID()
153
154 const regionMap = await getRegionMap(cacheId)
155
156 if (!regionMap) {
157 return new NextResponse(
158 "No valid regions configured. Please set up regions with countries in your Medusa Admin.",
159 { status: 500 }
160 )
161 }
162
163 const countryCode = await getCountryCode(request, regionMap)
164
165 if (!countryCode) {
166 return new NextResponse(
167 "No valid regions configured. Please set up regions with countries in your Medusa Admin.",
168 { status: 500 }
169 )
170 }
171
172 // Create response
173 const response = NextResponse.next()
174
175 // Set cache ID cookie if not set
176 if (!cacheIdCookie) {
177 response.cookies.set("_medusa_cache_id", cacheId, {
178 maxAge: 60 * 60 * 24,
179 })
180 }
181
182 // Set country code cookie if not set or different
183 const cookieCountryCode = request.cookies.get(COUNTRY_CODE_COOKIE_NAME)?.value
184 if (!cookieCountryCode || cookieCountryCode !== countryCode) {
185 response.cookies.set(COUNTRY_CODE_COOKIE_NAME, countryCode, {
186 maxAge: 60 * 60 * 24 * 365, // 1 year
187 httpOnly: false, // Allow client-side access
188 sameSite: "strict",
189 secure: process.env.NODE_ENV === "production",
190 })
191 }
192
193 return response
194 }
195 ```
196
197 In this updated `middleware` function, you make the following key changes regarding the country code:
198
199 1. Retrieve the country code using the updated `getCountryCode` function.
200 2. Set the country code cookie if it's not already set or if it differs from the current value.
201
202 With these changes, the middleware no longer requires the country code prefix in URLs and manages the country code using cookies instead.
203
204 ---
205
206 ## 3. Remove Routes from Country Code Prefix
207
208 Next, you need to restructure the routes in the Next.js Starter Storefront to remove the country code prefix.
209
210 Currently, there are two directories under `src/app/[countryCode]`: `(checkout)` and `(main)`. These directories contain all routes that include the country code prefix.
211
212 To remove the country code prefix, move the `(checkout)` and `(main)` directories directly under `src/app`, then delete the `[countryCode]` directory. Make sure to update any imports or references to and from the routes in these directories accordingly.
213
214 ![Diagram illustrating the directory structure before and after removing the country code prefix.](https://res.cloudinary.com/dza7lstvk/image/upload/v1767091142/Medusa%20Resources/nextjs-country-code-structure_wpm0yp.jpg)
215
216 ---
217
218 ## 4. Update Country Selector to Use Cookie
219
220 Next, you'll update the `CountrySelect` component that allows customers to select their country from the side menu. You'll modify it to set the country code cookie when a customer selects a different country, rather than changing the URL.
221
222 In `src/modules/layout/components/country-select/index.tsx`, add the following helper function before the `CountrySelect` component:
223
224 ```ts title="src/modules/layout/components/country-select/index.tsx"
225 // Helper function to get cookie value on client side
226 function getCookie(name: string): string | null {
227 if (typeof document === "undefined") {return null}
228 const value = `; ${document.cookie}`
229 const parts = value.split(`; ${name}=`)
230 if (parts.length === 2) {return parts.pop()?.split(";").shift() || null}
231 return null
232 }
233 ```
234
235 This function retrieves cookie values on the client side, allowing you to update the selected country in the dropdown based on the cookie value without refreshing the page.
236
237 Then, inside the `CountrySelect` component, add a new variable and update the `currentPath` variable declaration:
238
239 ```ts title="src/modules/layout/components/country-select/index.tsx"
240 const CountrySelect = ({ toggleState, regions }: CountrySelectProps) => {
241 const [countryCode, setCountryCode] = useState<string | null>(null)
242 const currentPath = usePathname()
243 // ...
244 }
245 ```
246
247 You define a new state variable `countryCode` to store the currently selected country code from the cookie. You also update the `currentPath` variable declaration to remove the country code retrieval from the URL.
248
249 Next, add the following functions in the `CountrySelect` component to handle country selection and changes:
250
251 ```ts title="src/modules/layout/components/country-select/index.tsx"
252 const CountrySelect = ({ toggleState, regions }: CountrySelectProps) => {
253 // ...
254
255 // Function to update country code from cookie
256 const updateCountryCodeFromCookie = () => {
257 const cookieCountryCode = getCookie("_medusa_country_code")
258 setCountryCode(cookieCountryCode)
259 }
260
261 useEffect(() => {
262 // Get country code from cookie on client side
263 updateCountryCodeFromCookie()
264
265 // Listen for focus events to refresh country code when user returns to the page
266 const handleFocus = () => {
267 updateCountryCodeFromCookie()
268 }
269
270 window.addEventListener("focus", handleFocus)
271 return () => window.removeEventListener("focus", handleFocus)
272 }, [])
273
274 const handleChange = async (option: CountryOption) => {
275 // Optimistically update the UI immediately
276 const newCountryCode = option.country.toLowerCase()
277 setCountryCode(newCountryCode)
278 const selectedOption = options?.find(
279 (o) => o?.country?.toLowerCase() === newCountryCode
280 )
281 if (selectedOption && selectedOption.country) {
282 setCurrent({
283 country: selectedOption.country,
284 region: selectedOption.region,
285 label: selectedOption.label,
286 })
287 }
288 close()
289
290 try {
291 // Update the region (this will set the cookie and redirect)
292 await updateRegion(option.country, currentPath)
293 } catch (error) {
294 // If update fails, revert to previous country code
295 updateCountryCodeFromCookie()
296 console.error("Failed to update region:", error)
297 }
298 }
299
300 // ...
301 }
302 ```
303
304 You add two functions:
305
306 1. `updateCountryCodeFromCookie`: Retrieves the country code from the cookie and updates the state.
307 2. `handleChange`: Handles country selection changes, optimistically updates the UI, sets the country code cookie, and reverts the UI if the update fails.
308
309 Then, update the `useEffect` usage in the component to the following:
310
311 ```ts title="src/modules/layout/components/country-select/index.tsx"
312 const CountrySelect = ({ toggleState, regions }: CountrySelectProps) => {
313 // ...
314
315 useEffect(() => {
316 if (countryCode) {
317 const option = options?.find(
318 (o) => o?.country === countryCode.toLowerCase()
319 )
320 setCurrent(option)
321 }
322 }, [options, countryCode])
323
324 // ...
325 }
326 ```
327
328 You make a small change to transform the country code to lowercase when finding the corresponding option.
329
330 Finally, in the return statement of the `CountrySelect` component, update the `defaultValue` prop of the `Listbox` component to the following:
331
332 ```tsx title="src/modules/layout/components/country-select/index.tsx"
333 const CountrySelect = ({ toggleState, regions }: CountrySelectProps) => {
334 // ...
335 return (
336 <div>
337 <Listbox
338 as="span"
339 onChange={handleChange}
340 defaultValue={
341 countryCode
342 ? (options?.find(
343 (o) => o?.country?.toLowerCase() === countryCode.toLowerCase()
344 ) as CountryOption | undefined)
345 : undefined
346 }
347 >
348 {/* ... */}
349 </Listbox>
350 </div>
351 )
352 }
353 ```
354
355 You update the `defaultValue` prop to find the option based on the country code stored in the cookie.
356
357 With these changes, the `CountrySelect` component now uses cookies to set and retrieve the country code instead of the URL.
358
359 ---
360
361 ## 5. Update Country Code Retrieval in Pages
362
363 Next, you'll update how the country code is retrieved across various pages of the Next.js Starter Storefront.
364
365 <Note>
366
367 The paths of the files mentioned in this section follow the new structure without the `[countryCode]` directory, as described in [Step 3](#3-remove-routes-from-country-code-prefix).
368
369 </Note>
370
371 ### a. Update Home Page
372
373 In `src/app/(main)/page.tsx`, add the following import at the top of the file:
374
375 ```ts title="src/app/(main)/page.tsx"
376 import { getCountryCode } from "@lib/data/cookies"
377 ```
378
379 Then, change the `Home` component to remove the `countryCode` parameter and retrieve the country code using the `getCountryCode` utility:
380
381 ```ts title="src/app/(main)/page.tsx"
382 export default async function Home() {
383 const countryCode = await getCountryCode()
384
385 if (!countryCode) {
386 return null
387 }
388
389 // ...
390 }
391 ```
392
393 ### b. Update Store Page
394
395 In `src/app/(main)/store/page.tsx`, add the following import at the top of the file:
396
397 ```tsx title="src/app/(main)/store/page.tsx"
398 import { getCountryCode } from "@lib/data/cookies"
399 ```
400
401 Then, remove the `params` prop from the `Params` type. It should only have a `searchParams` prop:
402
403 ```tsx title="src/app/(main)/store/page.tsx"
404 type Params = {
405 searchParams: Promise<{
406 sortBy?: SortOptions
407 page?: string
408 }>
409 }
410 ```
411
412 Finally, update the `StorePage` component to retrieve the country code using the `getCountryCode` utility:
413
414 ```tsx title="src/app/(main)/store/page.tsx"
415 export default async function StorePage(props: Params) {
416 const searchParams = await props.searchParams
417 const { sortBy, page } = searchParams
418 const countryCode = await getCountryCode()
419
420 if (!countryCode) {
421 return null
422 }
423
424 return (
425 <StoreTemplate
426 sortBy={sortBy}
427 page={page}
428 countryCode={countryCode}
429 />
430 )
431 }
432 ```
433
434 ### c. Update Product Page
435
436 In `src/app/(main)/products/[handle]/page.tsx`, add the following import at the top of the file:
437
438 ```tsx title="src/app/(main)/products/[handle]/page.tsx"
439 import { getCountryCode } from "@lib/data/cookies"
440 ```
441
442 Then, update the `Props` type to remove `countryCode` from the `params` prop:
443
444 ```tsx title="src/app/(main)/products/[handle]/page.tsx"
445 type Props = {
446 params: Promise<{ handle: string }>
447 searchParams: Promise<{ v_id?: string }>
448 }
449 ```
450
451 Next, update the `generateMetadata` function to retrieve the country code using the `getCountryCode` utility:
452
453 ```tsx title="src/app/(main)/products/[handle]/page.tsx"
454 export async function generateMetadata(props: Props): Promise<Metadata> {
455 const countryCode = await getCountryCode()
456
457 if (!countryCode) {
458 notFound()
459 }
460
461 const region = await getRegion(countryCode)
462
463 if (!region) {
464 notFound()
465 }
466
467 const product = await listProducts({
468 countryCode,
469 queryParams: { handle },
470 }).then(({ response }) => response.products[0])
471
472 // ...
473 }
474 ```
475
476 This retrieves the country code using the `getCountryCode` utility, then passes it to the `getRegion` and `listProducts` functions.
477
478 Finally, update the `ProductPage` component to retrieve the country code using the `getCountryCode` utility and pass it to the used functions and components:
479
480 ```tsx title="src/app/(main)/products/[handle]/page.tsx"
481 export default async function ProductPage(props: Props) {
482 const params = await props.params
483 const countryCode = await getCountryCode()
484 const searchParams = await props.searchParams
485
486 if (!countryCode) {
487 notFound()
488 }
489
490 const region = await getRegion(countryCode)
491
492 if (!region) {
493 notFound()
494 }
495
496 const selectedVariantId = searchParams.v_id
497
498 const pricedProduct = await listProducts({
499 countryCode,
500 queryParams: { handle: params.handle },
501 }).then(({ response }) => response.products[0])
502
503 const images = getImagesForVariant(pricedProduct, selectedVariantId)
504
505 if (!pricedProduct) {
506 notFound()
507 }
508
509 return (
510 <ProductTemplate
511 product={pricedProduct}
512 region={region}
513 countryCode={countryCode}
514 images={images}
515 />
516 )
517 }
518 ```
519
520 ### d. Update Collection Page
521
522 In `src/app/(main)/collections/[handle]/page.tsx`, add the following import at the top of the file:
523
524 ```tsx title="src/app/(main)/collections/[handle]/page.tsx"
525 import { getCountryCode } from "@lib/data/cookies"
526 ```
527
528 Then, update the `Props` type to remove `countryCode` from the `params` prop:
529
530 ```tsx title="src/app/(main)/collections/[handle]/page.tsx"
531 type Props = {
532 params: Promise<{ handle: string }>
533 searchParams: Promise<{
534 page?: string
535 sortBy?: SortOptions
536 }>
537 }
538 ```
539
540 Finally, update the `CollectionPage` component to retrieve the country code using the `getCountryCode` utility and pass it to the used component:
541
542 ```tsx title="src/app/(main)/collections/[handle]/page.tsx"
543 export default async function CollectionPage(props: Props) {
544 const searchParams = await props.searchParams
545 const params = await props.params
546 const { sortBy, page } = searchParams
547 const countryCode = await getCountryCode()
548
549 if (!countryCode) {
550 notFound()
551 }
552
553 const collection = await getCollectionByHandle(params.handle).then(
554 (collection: StoreCollection) => collection
555 )
556
557 if (!collection) {
558 notFound()
559 }
560
561 return (
562 <CollectionTemplate
563 collection={collection}
564 page={page}
565 sortBy={sortBy}
566 countryCode={countryCode}
567 />
568 )
569 }
570 ```
571
572 This retrieves the country code using the `getCountryCode` utility and passes it to the `CollectionTemplate` component.
573
574 ### e. Update Categories Page
575
576 In `src/app/(main)/categories/[...category]/page.tsx`, add the following import at the top of the file:
577
578 ```tsx title="src/app/(main)/categories/[...category]/page.tsx"
579 import { getCountryCode } from "@lib/data/cookies"
580 ```
581
582 Then, update the `Props` type to remove `countryCode` from the `params` prop:
583
584 ```tsx title="src/app/(main)/categories/[...category]/page.tsx"
585 type Props = {
586 params: Promise<{ category: string[] }>
587 searchParams: Promise<{
588 sortBy?: SortOptions
589 page?: string
590 }>
591 }
592 ```
593
594 Finally, update the `CategoriesPage` component to retrieve the country code using the `getCountryCode` utility and pass it to the used component:
595
596 ```tsx title="src/app/(main)/categories/[...category]/page.tsx"
597 export default async function CategoryPage(props: Props) {
598 const searchParams = await props.searchParams
599 const params = await props.params
600 const { sortBy, page } = searchParams
601 const countryCode = await getCountryCode()
602
603 if (!countryCode) {
604 notFound()
605 }
606
607 const productCategory = await getCategoryByHandle(params.category)
608
609 if (!productCategory) {
610 notFound()
611 }
612
613 return (
614 <CategoryTemplate
615 category={productCategory}
616 sortBy={sortBy}
617 page={page}
618 countryCode={countryCode}
619 />
620 )
621 }
622 ```
623
624 This retrieves the country code using the `getCountryCode` utility and passes it to the `CategoryTemplate` component.
625
626 ### f. Update Addresses Page
627
628 In `src/app/(main)/account/@dashboard/addresses/page.tsx`, add the following import at the top of the file:
629
630 ```tsx title="src/app/(main)/account/@dashboard/addresses/page.tsx"
631 import { getCountryCode } from "@lib/data/cookies"
632 ```
633
634 Then, update the `Addresses` component to remove the `countryCode` parameter and retrieve the country code using the `getCountryCode` utility:
635
636 ```tsx title="src/app/(main)/account/@dashboard/addresses/page.tsx"
637 export default async function Addresses() {
638 const countryCode = await getCountryCode()
639 const customer = await retrieveCustomer()
640
641 if (!countryCode) {
642 notFound()
643 }
644
645 // ...
646 }
647 ```
648
649 ---
650
651 ## 6. Update Country Usage in Components
652
653 In this section, you'll update various components in the Next.js Starter Storefront to use the country code from cookies instead of the URL.
654
655 ### a. Update AccountNav Component
656
657 In `src/modules/account/components/account-nav/index.tsx`, the country code is used to prefix URLs with the country code. You'll update it to remove the country code from the URLs.
658
659 In the `AccountNav` component, remove the country code retrieval using the `useParams` hook. You should have only the following lines before the `return` statement:
660
661 ```tsx title="src/modules/account/components/account-nav/index.tsx"
662 const AccountNav = ({
663 customer,
664 }: {
665 customer: HttpTypes.StoreCustomer | null
666 }) => {
667 const route = usePathname()
668
669 const handleLogout = async () => {
670 await signout()
671 }
672
673 // ...
674 }
675 ```
676
677 Then, in the `return` statement of the `AccountNav` component, change the condition checking the `route` variable's value to the following:
678
679 ```tsx title="src/modules/account/components/account-nav/index.tsx"
680 const AccountNav = ({
681 customer,
682 }: {
683 customer: HttpTypes.StoreCustomer | null
684 }) => {
685 // ...
686 return (
687 <div>
688 <div className="small:hidden" data-testid="mobile-account-nav">
689 {route !== `/account` ? (
690 {/* ... */}
691 ) : (
692 {/* ... */}
693 )}
694 </div>
695 {/* ... */}
696 </div>
697 )
698 }
699 ```
700
701 You remove the country code prefix from the URL checks in the `AccountNav` component.
702
703 Finally, in the `AccountNavLink` component defined in the same file, change the `active` variable declaration to the following:
704
705 ```tsx title="src/modules/account/components/account-nav/index.tsx"
706 const AccountNavLink = ({
707 href,
708 route,
709 children,
710 "data-testid": dataTestId,
711 }: AccountNavLinkProps) => {
712 const active = route === href
713
714 // ...
715 }
716 ```
717
718 You remove the country code prefix from the URL check in the `AccountNavLink` component.
719
720 ### b. Update ProductActions Component
721
722 The `ProductActions` component uses the country code when adding products to the cart. You'll remove the need to pass the country code to the `addToCart` function. You'll update the `addToCart` function later to retrieve the country code from the cookie.
723
724 In `src/modules/products/components/product-actions/index.tsx`, remove the `countryCode` variable from the `ProductActions` component:
725
726 ```tsx title="src/modules/products/components/product-actions/index.tsx"
727 export default function ProductActions({
728 product,
729 disabled,
730 }: ProductActionsProps) {
731 // ...
732
733 // REMOVE THIS LINE
734 // const countryCode = useParams().countryCode as string
735
736 // ...
737 }
738 ```
739
740 Then, in the `handleAddToCart` function inside the `ProductActions` component, remove the `countryCode` argument when calling the `addToCart` function:
741
742 ```tsx title="src/modules/products/components/product-actions/index.tsx"
743 export default function ProductActions({
744 product,
745 disabled,
746 }: ProductActionsProps) {
747 // ...
748
749 const handleAddToCart = async () => {
750 if (!selectedVariant?.id) {return null}
751
752 setIsAdding(true)
753
754 await addToCart({
755 variantId: selectedVariant.id,
756 quantity: 1,
757 // REMOVE THIS LINE
758 // countryCode,
759 })
760
761 setIsAdding(false)
762 }
763
764 // ...
765 }
766 ```
767
768 Ignore any type errors from the removed `countryCode` argument. You'll update the `addToCart` function later to remove the `countryCode` parameter.
769
770 ### c. Update LocalizedClientLink Component
771
772 The `LocalizedClientLink` component creates links that include the country code prefix in URLs. Update it to remove the country code from the URLs.
773
774 In `src/modules/common/components/localized-client-link/index.tsx`, replace the content with the following:
775
776 ```tsx title="src/modules/common/components/localized-client-link/index.tsx"
777 "use client"
778
779 import Link from "next/link"
780 import React from "react"
781
782 /**
783 * Use this component to create a Next.js `<Link />` that works without country code in the URL.
784 * Country code is now stored in a cookie instead.
785 */
786 const LocalizedClientLink = ({
787 children,
788 href,
789 ...props
790 }: {
791 children?: React.ReactNode
792 href: string
793 className?: string
794 onClick?: () => void
795 passHref?: true
796 [x: string]: any
797 }) => {
798 return (
799 <Link href={href} {...props}>
800 {children}
801 </Link>
802 )
803 }
804
805 export default LocalizedClientLink
806 ```
807
808 You make the following key changes:
809
810 1. Remove the `useParams` hook import and usage.
811 2. Remove the logic that adds the country code prefix to the `href` prop.
812
813 With these changes, the `LocalizedClientLink` component now creates links without the country code prefix in URLs.
814
815 ---
816
817 ## 7. Update Checkout Components
818
819 The checkout flow components also need to be updated to handle URLs without country codes. This includes forms and buttons that redirect to other checkout steps.
820
821 ### Update Checkout Navigation
822
823 In checkout components that handle navigation between steps (such as shipping, payment, and review), ensure that any redirect URLs or form actions don't include the country code prefix.
824
825 For example, if you have checkout step components that redirect to delivery or payment URLs, update them to use the new URL structure:
826
827 ```tsx
828 // Before: redirect(`/${countryCode}/checkout/delivery`)
829 // After: redirect(`/checkout/delivery`)
830 ```
831
832 ### Update Form Actions in Checkout
833
834 If your checkout forms have action URLs that include country codes, update them to the new structure. This is particularly important for:
835
836 - Shipping address forms
837 - Payment method selection
838 - Order review and confirmation
839
840 Look for any hardcoded URLs in checkout components and remove the country code prefix.
841
842 ---
843
844 ## 8. Update Server Functions to Use Country Code from Cookie
845
846 Finally, you'll update the server functions in the Next.js Starter Storefront to retrieve the country code from the cookie instead of receiving it as a parameter.
847
848 ### a. Update Customer Functions
849
850 In `src/lib/data/customer.ts`, find the `signout` function and update it to the following:
851
852 ```ts title="src/lib/data/customer.ts"
853 export async function signout() {
854 await sdk.auth.logout()
855
856 await removeAuthToken()
857
858 const customerCacheTag = await getCacheTag("customers")
859 revalidateTag(customerCacheTag)
860
861 await removeCartId()
862
863 const cartCacheTag = await getCacheTag("carts")
864 revalidateTag(cartCacheTag)
865
866 redirect(`/account`)
867 }
868 ```
869
870 You remove the `countryCode` parameter and the country code usage in the `redirect` function.
871
872 ### b. Update Cart Functions
873
874 In `src/lib/data/cart.ts`, add the following import at the top of the file:
875
876 ```ts title="src/lib/data/cart.ts"
877 import {
878 getCountryCode,
879 setCountryCode,
880 } from "@lib/data/cookies"
881 ```
882
883 Then, find the `addToCart` function and update it to the following:
884
885 ```ts title="src/lib/data/cart.ts"
886 export async function addToCart({
887 variantId,
888 quantity,
889 }: {
890 variantId: string
891 quantity: number
892 }) {
893 if (!variantId) {
894 throw new Error("Missing variant ID when adding to cart")
895 }
896
897 const countryCode = await getCountryCode()
898
899 if (!countryCode) {
900 throw new Error("Country code not found. Please select a country.")
901 }
902
903 const cart = await getOrSetCart(countryCode)
904
905 if (!cart) {
906 throw new Error("Error retrieving or creating cart")
907 }
908
909 const headers = {
910 ...(await getAuthHeaders()),
911 }
912
913 await sdk.store.cart
914 .createLineItem(
915 cart.id,
916 {
917 variant_id: variantId,
918 quantity,
919 },
920 {},
921 headers
922 )
923 .then(async () => {
924 const cartCacheTag = await getCacheTag("carts")
925 revalidateTag(cartCacheTag)
926
927 const fulfillmentCacheTag = await getCacheTag("fulfillment")
928 revalidateTag(fulfillmentCacheTag)
929 })
930 .catch(medusaError)
931 }
932 ```
933
934 You remove the `countryCode` parameter and retrieve the country code using the `getCountryCode` utility inside the function.
935
936 Next, find the `placeOrder` function in the same file and update it to the following:
937
938 ```ts title="src/lib/data/cart.ts"
939 export async function placeOrder(cartId?: string) {
940 const id = cartId || (await getCartId())
941
942 if (!id) {
943 throw new Error("No existing cart found when placing an order")
944 }
945
946 const headers = {
947 ...(await getAuthHeaders()),
948 }
949
950 const cartRes = await sdk.store.cart
951 .complete(id, {}, headers)
952 .then(async (cartRes) => {
953 const cartCacheTag = await getCacheTag("carts")
954 revalidateTag(cartCacheTag)
955 return cartRes
956 })
957 .catch(medusaError)
958
959 if (cartRes?.type === "order") {
960 const orderCacheTag = await getCacheTag("orders")
961 revalidateTag(orderCacheTag)
962
963 removeCartId()
964 redirect(`/order/${cartRes?.order.id}/confirmed`)
965 }
966
967 return cartRes.cart
968 }
969 ```
970
971 You change the redirect logic to remove the country code from the URL.
972
973 Finally, find the `updateRegion` function in the same file and update it to the following:
974
975 ```ts title="src/lib/data/cart.ts"
976 export async function updateRegion(countryCode: string, currentPath: string) {
977 const cartId = await getCartId()
978 const region = await getRegion(countryCode)
979
980 if (!region) {
981 throw new Error(`Region not found for country code: ${countryCode}`)
982 }
983
984 // Set country code cookie
985 await setCountryCode(countryCode)
986
987 if (cartId) {
988 await updateCart({ region_id: region.id })
989 const cartCacheTag = await getCacheTag("carts")
990 revalidateTag(cartCacheTag)
991 }
992
993 const regionCacheTag = await getCacheTag("regions")
994 revalidateTag(regionCacheTag)
995
996 const productsCacheTag = await getCacheTag("products")
997 revalidateTag(productsCacheTag)
998
999 redirect(currentPath || "/")
1000 }
1001 ```
1002
1003 You update the function to set the country code cookie using the `setCountryCode` utility instead of relying on the URL, and you remove the country code from the redirect URL.
1004
1005 ---
1006
1007 ## Test Your Changes
1008
1009 After completing these steps, you can use the Next.js Starter Storefront without country code prefixes in URLs. The country code is now managed using cookies.
1010
1011 To test it, run the following command in the directory of the Medusa application that the storefront connects to:
1012
1013 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
1014 npm run dev
1015 ```
1016
1017 Then, in a separate terminal, run the following command in the Next.js Starter Storefront directory to start the development server:
1018
1019 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
1020 npm run dev
1021 ```
1022
1023 You should be able to navigate the storefront, select different countries using the country selector, go through checkout, and place orders without country code prefixes in URLs. The country code is stored and retrieved using cookies as intended.