Skip to main content

Refreshing Your Token

Currently the recharge session will expire after one hour. While we are considering allowing the expiration of this session to be configurable or based your Shopify customer token, currently new ones will need to be fetched. In our experimentation the best way to do this is to create a component and API route that will periodically fetch a new Recharge session and update the Shopify session.

Example

You should already be referencing RechargeLogin from RechargeClient.server.tsx created under Initialization. This component will periodically make an API call to refetch a Recharge Session and update the Shopify session so it is available for all of your calls to the Recharge. Create the client component and API route below.

Client component - /src/components/RechargeLogin.client.tsx

import { useEffect } from 'react';

// 30 minutes
const INTERVAL = 1000 * 60 * 30;

interface Props {
loggedIn: boolean;
}

// Example of client side keep alive
export function RechargeLogin({ loggedIn }: Props) {
useEffect(() => {
const update = async () => {
try {
await fetch('/account/recharge', { method: 'POST' });
} catch {
console.error('recharge token update failed.');
}
};

const interval = setInterval(() => {
if (loggedIn) {
update();
}
}, INTERVAL);
return () => clearInterval(interval);
}, [loggedIn]);
return null;
}

API Route - /src/routes/account/recharge.server.tsx

import { loginShopifyApi } from '@rechargeapps/storefront-client';
import { HydrogenApiRouteOptions, HydrogenRequest } from '@shopify/hydrogen';
import { ShopifyConfig } from '@shopify/hydrogen/shared-types';

export async function api(request: HydrogenRequest, { session, hydrogenConfig }: HydrogenApiRouteOptions) {
if (!session) {
return new Response('Session storage not available.', { status: 400 });
}

const { customerAccessToken } = await session.get();

if (customerAccessToken) {
const { storefrontToken } = hydrogenConfig.shopify as ShopifyConfig;
try {
const rechargeSession = await loginShopifyApi(storefrontToken, customerAccessToken);

if (rechargeSession) {
await session.set('rechargeSession', JSON.stringify(rechargeSession));
return new Response(null, {
status: 201,
});
}
} catch (error: any) {
return new Response(
JSON.stringify({
error: error.message,
}),
{
status: 500,
}
);
}
} else {
return new Response(
JSON.stringify({
error: 'No customerAccessToken available',
}),
{ status: 401 }
);
}
}