Last active
October 20, 2022 19:25
-
-
Save benjaminsehl/f6ecbb053bd6d42289881bd8633fb981 to your computer and use it in GitHub Desktop.
A rough implementation of discount links in Hydrogen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Place this file at `/routes/discounts/[handle].tsx` | |
import {useUrl, useRouteParams, useSession} from '@shopify/hydrogen'; | |
// @TODO: Add in API route for setting session cookie with discount code: https://shopify.dev/custom-storefronts/hydrogen/framework/sessions#reading-and-updating-session-data | |
export async function api(request, {session}) { | |
let sessionData, jsonData; | |
} | |
export default function DiscountLink({response}} { | |
const url = useUrl(); | |
const {handle} = useRouteParams(); | |
if (response && response.writeHead) { | |
response.doNotStream(); | |
response.writeHead({status: 302}); | |
} | |
if (handle) { | |
// @TODO: Call API route here to set discount code (handle) as discountCode cookie on session | |
} | |
const target = url.searchParams.get('redirect_to') | |
if (target) { | |
return response.redirect(target) | |
} else { | |
return response.redirect('/') | |
} | |
} | |
/* | |
Note, if implementing client side redirects in Online Store similar to: https://gist.github.com/benjaminsehl/cdd0ce53951659db1266276cda854285 | |
Then an additional API route will be needed, or similar logic, to grab the `discount_code` URL parameter, and save it in the `discountCode` cookie slot | |
A better design for both cases may be to have a dedicated /api/discount_link.server.tsx API route which handles both the Online Store redirect case, and the | |
Hydrogen-native discount link case. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment