skip to Main Content

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

}

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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 😀

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search