What I managed to do so far
I followed this guide to setup a Shopify app with a Rails backend + React: https://medium.com/@esimonian16/setting-up-a-shopify-app-with-rails-5-1-webpack-react-and-polaris-b8535d911275
Everything seems to work fine. I'm using the shopify_app gem.
When I navigate to my app in the merchant dashboard, The home controller in Rails renders a React app which displays some products (these were passed from rails to react as json).
What I would like to do now
I want to have a button in React 'List customers', which should then update the react components and show all the customers as a list.
I have created a new controller at my-app.com/customers
class CustomersController < ShopifyApp::AuthenticatedController
def index
customers = ShopifyAPI::Customer.find(:all, params: { limit: 10 })
render json: customers
end
end
If I go to my-app.com/customers
in the browser I get the correct json response.
I then tried fetching this data from React.
fetch('https://my-app.com/customers', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(parsedJSON => {
console.log(parsedJSON);
// Update state
// this.setState(...);
})
.catch(error => console.error(error));
The Rails backend doesn't allow the request to get this data, because it is not authorized, so it get's redirected to /login
In React, I have access to the session.token
, however I'm not sure how to use it to authenticate my request?
Questions
- How do I make such calls to the Shopify API? Am I trying the right approach, i.e use my backend between React and the actual Shopify Api call?
- How do I authenticate my call so that they pass just as if I'm calling
/customers
in the browser? - I guess making Shopify Api calls directly from React would be a really bad idea, because I would expose my secrets to the world, right?
- What am I doing wrong? What is the correct approach?