I have a test database in MongoDB Atlas. Using the MongoDB Realm service, I've been able to set up a GraphQL endpoint for the database.
I can run queries internally with their sandbox (GraphiQL).
After configuring the API key auth provider...
...I was able to run queries externally from Postman, calling https://realm.mongodb.com/api/client/v2.0/app/<MY_APP_ID>/graphql
.
However, trying to make the same call using axios...
await axios({
method: 'POST',
url:
'https://realm.mongodb.com/api/client/v2.0/app/<MY_APP_ID>/graphql',
headers: {
apiKey: '<MY_API_KEY>',
'Content-Type': 'application/json',
},
data: {
query: `
{
item {
_id
name
description
}
}
`
}
})
...gives a CORS error.
Is there something I need to configure in Realm or a header that I'm missing to allow external access to the GraphQL endpoint from the browser?
After discovering the Task Tracker (web) tutorial in the MongoDB Realm documentation I realized the issue. I needed to use the Realm javascript SDK to log in to Realm using my app ID and an auth provider.
You can use any auth providers you've enabled in the Realm dashboard (username/password, API key, Google, etc.) but they all return a single bearer token on sign in. This bearer token is what allows cross-domain querying of the GraphQL endpoint.
I also broke down and decided to install Apollo Client to do all the talking to the endpoint. The source for the React solution I ultimately ended up implementing can be found here. It uses a RealmApp
to communicate with Realm and a RealmApolloProvider
to talk to GraphQL with the proper Realm auth token.