How can I pass Request with bearer/auth using fetch (or axios) api and be able to validate authorization?

I have a page in my Shopify Remix React app using code like the below. My question is how do I add the request headers that Shopify is expecting to authenticate the admin request? fetch('/api/geocode', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({orders}) }).then(res => res.json()).then(data => { console.log('geocode data', data) }) On my api.geocode.js I want to validate that they are authorized: export async function action({request}) { const { admin } = await authenticate.admin(request); // does not work const data = await request.json(); }

Comment (2)

Jese Leos

August 19, 2024

Verified user

To authenticate the request to Shopify's Admin API, you'll need to include the appropriate headers, such as the X-Shopify-Access-Token, in your fetch request. These headers will be used on the server side to validate the request. Here’s how you can modify your code to include these headers and authenticate the request on the server side. #Frontend Code #Update your fetch call to include the necessary headers for authentication: fetch('/api/geocode', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': 'YOUR_ACCESS_TOKEN', // Replace with your access token }, body: JSON.stringify({ orders }) }) .then(res => res.json()) .then(data => { console.log('geocode data', data); }) .catch(error => { console.error('Error:', error); }); #Backend Code #On the server side, you will validate the request by checking the headers. Here’s how you can update the api.geocode.js: import { authenticate } from './path-to-your-authentication-module'; export async function action({ request }) { const authHeader = request.headers.get('X-Shopify-Access-Token'); // Validate the access token if (!authHeader || authHeader !== process.env.SHOPIFY_ACCESS_TOKEN) { return json({ error: 'Unauthorized' }, { status: 401 }); } const data = await request.json(); // Proceed with your logic... return json({ success: true, data }); } Run code snippetExpand snippet Let me know if this helps :D

Jese Leos

August 19, 2024

Verified user

You can get token from localstorage if you already login into app const token = localStorage.getItem('token'); After that yo can easily validate if token has header Auth const authHeader = request.headers.get('Authorization'); if (!authHeader) { return json({ error: 'Authorization header missing' }, { status: 401 }); } But if you want to validate if this token valid you can use jsonwebtoken with your secret key It will be something like this const decoded = jwt.verify(token, secretKey);

You’ll be in good company