javascriptshopify

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();
}

Solution

  • 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 });
    }

    Let me know if this helps :D