Tips for including a header with Apollo Client in a React Native app

In my React Native application, here's how I set up the Apollo client with an upload link:

My goal is to include a header with a token value that will be sent with every request. However, I've had trouble finding an example specifically for React Native.

import { AsyncStorage } from 'react-native'
import { ApolloClient } from 'apollo-client'
import { createUploadLink } from 'apollo-upload-client'
import { InMemoryCache } from 'apollo-cache-inmemory'

const client = new ApolloClient({
  link: createUploadLink({
    uri: 'http://localhost:3000/graphql'
  }),
  cache: new InMemoryCache()
})

The following code snippet shows how I want to send the token value in the header:

const token = await AsyncStorage.getItem('auth.token')

Update

I'm trying to figure out how to insert the token from AsyncStorage into the header. The use of await won't work here because it's not within an async function:

const token = await AsyncStorage.getItem('auth.token') // await can't work here

// Initialize apollo client
const client = new ApolloClient({
  link: createUploadLink({
    uri: 'http://localhost:3000/graphql',
    headers: {
      authorization: token
    }
  }),
  cache: new InMemoryCache()
})

// Wrap apollo provider
const withProvider = (Component, client) => {
  return class extends React.Component {
    render () {
      return (
        <ApolloProvider client={client}>
          <Component {...this.props} client={client} />
        </ApolloProvider>
      )
    }
  }
}

export default async () => {
  Navigation.registerComponent('MainScreen', () => withProvider(MainScreen, client))

  Navigation.startSingleScreenApp({
    screen: {
      screen: 'MainScreen'
    }
  })
}

Answer №1

createUploadLink comes with a headers attribute that corresponds to the headers attribute of createHttpLink.

headers: an object containing values to be included as headers in the request.

Example

const token = await AsyncStorage.getItem('auth.token')

const client = new ApolloClient({
  link: createUploadLink({
    uri: 'http://localhost:3000/graphql',
    headers: {
      "Some-Custom-Header": token
    }
  }),
  cache: new InMemoryCache()
})

UPDATE

const getToken = async () => {
  const token = await AsyncStorage.getItem('auth.token')
  return token
}
const token = getToken()
// Initialize apollo client
const client = new ApolloClient({
  link: createUploadLink({
    uri: 'http://localhost:3000/graphql',
    headers: {
      authorization: token
    }
  }),
  cache: new InMemoryCache()
})
// Add apollo provider wrapper
const withProvider = (Component, client) => {
  return class extends React.Component {
    render () {
      return (
        <ApolloProvider client={client}>
          <Component {...this.props} client={client} />
        </ApolloProvider>
      )
    }
  }
}

export default async () => {
  Navigation.registerComponent('MainScreen', () => withProvider(MainScreen, client))

  Navigation.startSingleScreenApp({
    screen: {
      screen: 'MainScreen'
    }
  })
}

Answer №2

I recently started using apollo boost, and my approach was as follows:

import ApolloClient from 'apollo-boost';

const client = new ApolloClient({
  uri: 'http://localhost:3000/graphql',
  request: async (operation) => {
    const token = await AsyncStorage.getItem('token');
    operation.setContext({
      headers: {
        authorization: token
      }
    });
  }
}

Answer №3

Implementing a callback with getItem also proves to be effective

import { ApolloClient, HttpLink, ApolloLink, InMemoryCache } from 'apollo-boost'

const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql',
})

const authLink = new ApolloLink((operation, forward) => {
  AsyncStorage.getItem('AuthToken').then(token => {
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : '',
      },
    })
  })
  return forward(operation)
})

const apolloClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: authLink.concat(httpLink),
})

Answer №4

In June 2021, I devised a solution in the form of a gist file that can be utilized with both AsyncStorage and React-Redux. This solution eliminates the need for additional dependencies like apollo-boost, especially if you are already using apollo-client. Give it a try and hopefully, it will work seamlessly for you.

Just a heads up:

This implementation is specifically designed to help you set up token or authentication headers on your apoll-client graphql requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...

"Using Nightwatch.js to Trigger a Click Event on a Text Link

My goal is to use Nightwatch for testing the login process by clicking on a log in text link. I came across this helpful article: How to click a link using link text in nightwatch.js. The article suggested using the following code: .useXpath() // ever ...

Adding data to an AngularJS template

I am encountering an issue with a flag that I am toggling between true and false to alter the display of certain elements on my page. While it works outside of the template, integrating this value into the template itself has proven challenging. restrict: ...

What are the steps to add a Search Box to my HTML Website?

Currently, I am in search of a way to incorporate a "Search" feature on my website that is built solely with HTML. I have added a Search box for the users but I'm uncertain about how to proceed next. Can I use PHP to enable the Search functionality o ...

While v-carousel adjusts to different screen sizes, the images it displays do not adapt to

Whenever I implement v-carousel, everything seems to be working well, but there is an issue on mobile. Despite the carousel itself being responsive, the images inside do not resize properly, resulting in only the center portion of each image being displaye ...

Setting up Karma configuration to specifically exclude nested directories

When unit testing my Angular 2 application using Karma, I encountered an issue with my directory structure: └── src/ ├── index.js ├── index.js.text ├── index.test.js ├── README.txt ├── startuptest.js ...

Refresh an iframe smoothly and without any visual distraction (using JavaScript)

Does anyone have a clever solution to dynamically refresh an iframe without the annoying flickering or flashing that usually occurs when the page reloads? Is it possible to incorporate a smooth blur-out and blur-in animation instead of the unappealing flic ...

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

Create original identifiers for dynamically generated material

I have developed a custom invoice tool that has the capability to dynamically add rows. Here is the code snippet responsible for generating new rows: $("#addrow").click(function(){ $(".item-row:last").after('<tr class="item-row"><td> ...

An issue encountered with getServerSideProps in NextJS 12 is causing a HttpError stating that cookies are not iterable, leading

Currently, I have an application running smoothly on my localhost. However, when it comes to production, an unexpected error has popped up: Error: HttpError: cookies is not iterable at handleError (/usr/src/.next/server/chunks/6830.js:163:11) at sendReques ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

Problem with Ajax causing full-page reload

I currently have a webpage that utilizes JqueryUI-Mobile (specifically listview) in conjunction with PHP and some Ajax code. When the page loads initially, it displays a list generated from a MySQL DB. I want this list to refresh itself periodically witho ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

JavaScript Ajax request lags significantly in Internet Explorer, while it executes instantly in Firefox

So I have this jQuery .ajax() call set up to retrieve a List<string> of IP addresses from a specific subnet. I'm using a [WebMethod] on an .aspx page to handle the request and ASP.NET's JSON serializer to format the response for my Javascri ...

Backend undergoing fluctuations in hourly values

When passing JS dateTime to the backend using ajax(axios), I encountered a discrepancy in the timestamps. Prior to the post request, I have the following timestamp: Sun Nov 04 2018 21:53:38 GMT+0500 However, upon reaching the backend, the timestam ...

Incorrect Results from Angular Code Coverage

Currently using Angular.js, Karma, Karma-coverage (Istanbul), and Jasmine for my stack. While conducting Code Coverage analysis on my app, I encountered an issue which leads to my question - Service A is showing up as covered by tests (in green) even thou ...

What is the best way to incorporate the "child_process" node module into an Angular application?

Trying to execute a shell script in my Angular application has been quite the challenge. I came across the "child process" node library that might be able to help me with this task. However, every attempt to import the library led me to the error message: ...

Creating a RESTful API

To begin with, I am a newcomer to web frameworks and we are currently using Meteor. In our database, we have a collection of Students: Students = new Mongo.Collection('students'); At the moment, we have defined a Rest API as follows: // Maps t ...

Discover the correct way to locate the "_id" field, not the "id" field, within an array when using Javascript and the MEAN stack

I am working on an Angular application that connects to MongoDB. I have a data array named books, which stores information retrieved from the database. The structure of each entry in the array is as follows: {_id: "5b768f4519d48c34e466411f", name: "test", ...