Navigating Express HTTP Requests within Apollo Link Context in a NextJS Web Application

Currently, I am in the process of developing a NextJS application and facing a challenge with accessing a cookie to utilize it for setting a Http Header within a GraphQL Request. For this task, I am integrating apollo-link-context. Below is the snippet of code responsible for creating the ApolloClient.

function createApolloClient(initialState = {}) {
  const httpLink = new HttpLink({ uri: `${baseUrl}/graphql`, credentials: 'same-origin', fetch })

  const authLink = setContext((_, prevCtx) => {
    let token = ''
    if (typeof window === 'undefined') token = getCookieFromServer(authCookieName, REQ)
    else token = getCookieFromBrowser(authCookieName)
    return ({ headers: { 'Auth-Token': token } })
  })

  const client = new ApolloClient({
    ssrMode: typeof window === 'undefined',
    cache: new InMemoryCache().restore(initialState),
    link: authLink.concat(httpLink)
  })

  return client
}

A hurdle arises as the getCookieFromServer function requires an Express Request as its second parameter to extract the cookie from req.headers.cookie. At present, I am uncertain about where to procure this information.

Answer №1

After much trial and error, I have finally discovered a solution. By sending a request from the server (in PageComponent.getInitialProps) and setting the header in the context, I am able to access it from setContext:

PageComponent.getInitialProps = async (ctx) => {
  ...
  const token = getCookieFromServer(authCookieName, ctx.req)
  const { data } = await client.query({
    query,
    context: { headers: { 'Auth-Token': token } }
  })
  ...
}

In the setContext function:

const authLink = setContext((_, prevCtx) => {
  let headers = prevCtx.headers || {}

  if (!headers['Auth-Token']) {
    const token = getCookieFromBrowser(authCookieName)
    headers = { ...headers, 'Auth-Token': token }
  }

  return ({ headers })
})

This approach allows me to use the existing header if it is already present in the previous context (sent from the server), or retrieve the cookie from the browser and set it if it is not present (sent from the browser).

I hope this explanation proves useful to someone in need one day.

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

Avoiding a jest compile error and executing the test efficiently

Here is my Vue.js code snippet: export default { name: 'App', components: { }, created() { let t = typeof t === 'undefined' ? {} : t; // ISSUE LINE } } The ISSUE LINE runs successfully in the browser without any errors an ...

Unique button for custom "CODE" in Froala

Looking to create a custom button with functionality similar to bold (B) but for source code (Src). I have attempted the following, however it is not fully functional: $("#elm1").editable({ inlineMode: false, minHeight: 300, buttons: ["src"], c ...

What is the best way to capture a screenshot of a website using its URL?

I've been curious about the possibility of capturing a screenshot of a remote website using only a URL and some JavaScript code. This functionality is often seen on bookmarking sites. I can't help but wonder if this is achieved through a virtual ...

Is Firebase the Answer to Shopify's Authentication Validation?

I've been following this tutorial on building a Shopify app using Node, Nextjs, and React. Progress has been smooth so far, but I've now reached a point where I need to store some of my app data in Firestore. My current approach involves utiliz ...

Update the browser URL dynamically without redirecting the page, by utilizing JavaScript after an AJAX call receives a

I am currently endeavoring to find a solution to replace the URL on my page without triggering a reload. My approach involves utilizing an infinite scroll JavaScript plugin. Upon receiving a response from an AJAX call, I intend to update the URL with the n ...

Show Angular if it is in the array

Presently, I have an ng-repeat function to display comments on articles. It is structured like this: <div ng-repeat="comment in comments"> <li class="item" ng-class-even="'even'"> <div class="row"> ...

Storage can be shared globally in a React/Nextjs application

My current situation involves retrieving data through an application, however I am encountering 429 errors due to server limits restricting infinite requests. To address this issue, my plan is to fetch data nightly and store it in a centralized storage ac ...

How can I use VueJS and Vue Router to generate a details page for a list item?

I am currently working with a list of items sourced from a JSON file and looping through them. However, I want to create individual details pages for each item using VueRouter. Any advice on how I can accomplish this? I am facing difficulties in passing t ...

The mysterious nature of view binding in Ember.js

Here's a unique challenge I'm facing. I've developed a sidebar component called SortableStopView that extends CollectionView. This sidebar contains a scrollable and sortable list of 'stops' which users can click on to navigate to t ...

How can I retrieve the second letter in Materialize CSS FormSelect by using the keyboard?

On my website that utilizes materializeCSS and Jquery, I have encountered an issue with a select box containing numerous options. Typically, when using a select box, I can press a letter multiple times to cycle through options starting with that letter. ...

Step-by-step guide to selecting a specific point on an HTML5 canvas using Python's selenium webdriver

Looking to automate interactions with a simple HTML5 application on a website using Selenium webdriver in Python with Firefox on Linux. The challenge is clicking a button on an HTML5 canvas, then dragging one or two objects around the canvas post-button cl ...

Grab the div, position it accurately, and initiate an ajax call

So many tasks on my plate, but let's prioritize. Within a <div class="showcase">, I have numerous <div class="game"> elements, each with an onclick="addpop('delpopup.php?id=something&pos=somethingelse&box=image')" Does ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

Exploring the possibilities of combining OpenCV with web technologies like Javascript

I am currently faced with the challenge of integrating OpenCV into a web application using Express.js. While I am familiar with the Python and C++ libraries for OpenCV, I now need to work with it in conjunction with Express.js. My main requirements include ...

Using JQuery and Javascript to retrieve information from one drop down list based on the selection made in another drop down

I'm currently working on a project that involves 2 drop-down menus. The first menu allows you to select a general model, while the second menu displays specific models based on your selection. http://jsfiddle.net/QskM9/ Here's an example of how ...

What steps can I take to resolve the hydration issue with the authenticating component?

My current setup involves an authentication component that verifies whether the user has a token stored in local storage. Below is a snippet of the code: import { useRouter } from "next/router"; import { useState } from "react"; const ...

When located at the bottom of a page, the Div element fails to display

I need some help with my javascript code. I am working on creating a scrollable panel that closes when scrolled and reveals a #toTop div when the bottom of the page is reached. Below is the function code I have written, but for some reason, the #toTop div ...

When using angularjs, the $window.location.href may cause the page to load without any

I have a dilemma where I have linked all my CSS and JS files in the index.html file, but subpages are located in a templates directory. When using $window.location.href, only a plain HTML page is returned without any CSS styles. The page renders fine when ...

blending javascript and php variables within ajax requests

I am working on a simple jQuery ajax feature, where I need to combine form data retrieved by JS with some PHP variables and send them all through ajax GET method. Here's what I have: var longform = $("input:text").serialize(); $.ajax({ url: & ...

How do Nodejs and Express contribute to the functionality of a MERN stack website that incorporates GraphQL?

As a beginner, I am struggling to understand certain aspects of the MERN stack and GraphQL. I came across this specific project on github that utilizes MongoDB, Express, React, Nodejs, and GraphQL. I comprehend that MongoDB is used for data storage and Re ...