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

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

I am experiencing an issue where Swagger UI and express-basic-auth are consistently returning a 401 error on all my routes, instead of the specified error

I have set up a swagger implementation and added simple authentication validation with express-basic-auth before allowing access to the UI. However, this implementation is causing every route to return a 401 error. All my routes are now broken as the midd ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Is there a C++ equivalent to the JS Array.prototype.map method?

When it comes to JavaScript, Array.prototype.map is a powerful tool for creating a new array by applying a function to each element. Consider the following example: const elements = [{ text: 'hi1' }, { text: 'hi2' }, { text: 'hihi ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

What is the best way to keep calling an AJAX function until it receives a response from a previous AJAX call

I am looking to continuously call my ajax function until the previous ajax call receives a response. Currently, the page is loading every second and triggering the ajax function, but I want it to keep calling the ajax function until the previous one has c ...

The input form in my Node.js project is not adapting to different screen sizes. I am currently utilizing ejs as the template

I have integrated ejs as a template in my Node.js project, but I am encountering an issue with the input form in the following code snippet. The form is unresponsive, preventing me from entering text or clicking on any buttons. What could be causing this ...

Utilize jQuery to append YQL output in JSON format to specific IDs in your code

I have a YQL output JSON string at this URL: Check out the YQL JSON here I encountered some other I am exploring why I am facing difficulties in extracting certain items from the returned JSON. For instance, when using jQuery to access the H1 tag within ...

Tips for editing events in the "react-big-calendars" component

I am looking to implement a feature where users can click on events in a calendar and then edit either the dates or event titles. Can this functionality be achieved using "react-big-calendar"? If not, are there any other packages you can recommend? <Cal ...

Show the value in the input text field if the variable is present, or else show the placeholder text

Is there a ternary operator in Angular 1.2.19 for templates that allows displaying a variable as an input value if it exists, otherwise display the placeholder? Something like this: <input type="text "{{ if phoneNumber ? "value='{{phoneNumber}}&a ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Encountering issues with configuring an Express server with HTTPS

Having difficulty setting up my Express server on HTTPS and accessing my API. Below is the code I am using: // server.js const express = require('express'); const { readFileSync } = require('fs'); const https = require('https' ...

Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like: T = { a: 2, b: 9, c: { a: 3, d: 6, e: { f: 12 } } } The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototy ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Jest - experiencing intermittent test failures on initial run, yet succeeding on subsequent runs

Writing tests with jest and supertest npm on a node server has been a challenge for me. When I try to run all the tests together, some of them fail inexplicably: However, if I selectively run only the failed tests in the terminal, they pass without any is ...

Using jQuery to select the child element of the parent that came before

Recently, I've been experimenting with creating animations using CSS and jQuery. While it has been successful so far, I'm now looking to take it a step further. Specifically, I want information to appear on top of an image when the user clicks on ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

error - Uncaught ReferenceError: Unable to use 'auth' before initializing

I am currently following an online tutorial on building a WhatsApp clone and I encountered a problem. import "../styles/globals.css"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db } from "../f ...

Hide the popup by clicking anywhere outside of it

I need help with a code that involves a button triggering a popup, and I want the user to be able to close the popup by clicking outside of it when it's open. My goal is to assign the method "Close()" to the event listener that detects clicks outside ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...