I am working on a Shopify Remix app with a Customer UI extension and need to retrieve the currently logged-in customer ID. How to get the customer id?
Hi @greeshma
In a Remix app, you can access the customer ID through Shopifyâs authenticated context since the extension runs in a logged-in customerâs session. Use the @shopify/shopify-api or Remixâs loader function to fetch itâinside your loader,call shopify.authenticated.customer() to get the customer object, which includes the id. It might look like this: export async function loader({ context }) { const customer = await context.shopify.authenticated.customer(); return json({ customerId: customer.id }); }. Make sure your appâs scopes include read_customers in the shopify.app.toml file to access this data. Test it in your dev environment to ensure it pulls the right ID
@Promer Hi,
I tried your suggestion, but found a CORS policy error. To resolve this, I added the following headers to the response:
headers: {
âAccess-Control-Allow-Originâ: â*â
}
However, the issue persists. The error message states:
âAccess to fetch at âhttps://inquiry-spyware-meetings-vote.trycloudflare.com/api/getwishlistâ from origin âhttps://extensions.shopifycdn.comâ has been blocked by CORS policy: Response to preflight request doesnât pass access control check: It does not have HTTP OK status.â
Below is my current code:
import { json } from â@remix-run/nodeâ;
export async function loader({ context }) {
const customer = await context.shopify.authenticated.customer();
return json(
{ customerId: customer.id },
{
headers: {
âAccess-Control-Allow-Originâ: â*â
},
}
);
}
Could you please help me resolve this issue? Your assistance would be greatly appreciated
I found a solution for retrieving the customer ID in a Shopify Customer Account UI Extension app.
To get the authenticated customerâs ID, add the following code in the JavaScript file located in the src folder:
const customerId = api.authenticatedAccount?.customer?.current?.id;
- api.authenticatedAccount provides authentication details of the currently logged-in account.
- .customer accesses the customer-related information.
- .current refers to the authenticated customer.
- .id retrieves the unique identifier of the customer.
Wow, thanks for sharing me this solution, Iâll note it. Thanks for letting me know!