Establishing Authorization Headers in ApolloClient for every individual request

Currently, I am expanding my knowledge on GraphQL and Next.js by taking a course on Udemy. The course instructor utilizes ApolloClient from the apollo-boost package, but I have opted to use the newer @apollo/client package instead.

In the original method using apollo-boost's ApolloClient, the author sets credentials for each request as shown below:

new ApolloClient({
      request: operation => {
        operation.setContext({
          fetchOptions: {
            credentials: 'include'
          },
          headers
        })
      },
      uri: process.env.BASE_URL,
      cache: new InMemoryCache().restore(initialState || {})
})

The above approach did not work for me, as the request property is not present in the @apollo/client's ApolloClient. My alternative solution was as follows:

const link = new HttpLink({ uri: "http://localhost:3000/graphql", credentials: 'include' });
new ApolloClient({
      cache: new InMemoryCache().restore(initialState || { }),
      link,
    })

However, the credentials were not being applied to each request, leading to a lack of user information retrieval. In my setup, I utilize passport which stores logged-in user information in cookies. Below is an excerpt from my index.js file showcasing how passport is configured:

const config = require('../config/dev');
const sessison = require('express-session');
const passport = require('passport');
exports.init = (server, db) => {
  require('./passport').init(passport);
  const sess = {
    name: 'portfolio-session',
    secret: config.SESSION_SECRET,
    cookie: { maxAge: 2 * 60 * 60 * 100},
    resave: false,
    saveUninitialized: false,
    store: db.initSessionStore()
  }

  server.use(sessison(sess));
  server.use(passport.initialize());
  server.use(passport.session());
}

If anyone has insights or suggestions on how to add authentication to ApolloClient, your assistance would be greatly appreciated.

Thank you :)

Answer №1

It seems that in the provided example, the header containing the token is not being passed correctly. Refer to the headers used in the first author's example:

[...]
   fetchOptions: {
            credentials: 'include'
          },
          headers // <- this one
        })
      },
[...]

Include the header in the request as shown below:

const link = new HttpLink({ 
  uri: "http://localhost:3000/graphql", 
  headers // <-- include it here, should be something like: { Authorization: `Bearer ${token}` } or similar
});
const client = new ApolloClient({
   cache: new InMemoryCache().restore(initialState || { }),
   link,
});

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

How to efficiently initialize a Next.js app with Phusion Passenger while triggering the production build using a specific file?

In most cases, a Next.js application is launched by using the command npm run start after compiling it with npm run build. I am unable to start it using a command because my web server stack (Phusion Passenger) requires a specific startup script. https:// ...

NextJS is encountering an issue with Axios' withCredentials functionality

I'm facing an issue where Axios is not sending the cookie to my backend API, even though I have set the withCredentials properly. Front-end (NextJS): import axios from "axios" const BASE_URL = "http://localhost:8000" export defa ...

Avoiding the installation of dependencies within npm packages, particularly in projects utilizing Next.js, Node

I've encountered a puzzling issue that seems to have no solution online. When I install npm packages, their dependencies are not automatically installed. This situation is resulting in numerous warnings appearing in the console, such as: Module not ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Having trouble resolving '@auth0/nextjs-auth0' during deployment on Vercel? Check out this error message: "Can't resolve '@auth0/nextjs-auth0' in '/vercel/path0/pages'"

I recently deployed a project on Vercel and have been working on enhancing the layout to achieve a minimum viable product (MVP). As part of this process, I decided to switch my authentication method to @auth0/nextjs-auth0 package for Next.js. After running ...

Unlock the full potential of integrating external APIs with Next.js

As a newcomer to NextJs, I am facing the task of making calls to an external Python API from my frontend. Upon discovering NextJs's integrated API feature through creating folders in the app directory, namely api/resource/route, I am wondering what th ...

Is it possible to create custom input fields using the Stripes Payment-Element?

I recently integrated Stripe into my next.js application to facilitate one-time payments. Following the standard tutorial for Stripe Elements, I created a PaymentIntent on initial render: useEffect(() => { // Create PaymentIntent as soon as the ...

Encountered an issue loading next.config.js during the build process with GitHub actions

Currently, I am utilizing a straightforward ssh deploy action along with a bash script designed to both build and restart the pm2 frontend process. Everything seems to be running smoothly when executing the script directly on the ec2 instance. However, is ...

Sending information from Axios to Danfo using NextJs is seamless and efficient

I am currently developing a NextJs page where I have incorporated axios along with useState and useEffect to fetch JSON data from a web API and store it in a state called 'apiData'. .then((res) => { setApiData(res.data.Projects); conso ...

Ways to halt the expressjs server

After deploying my express and nextjs based app on EC2, I encountered an issue where the server automatically starts Nginx and node with different process IDs after I attempt to stop it by killing the process. This is happening even without using tools lik ...

Forward multipart requests in NextJS (as well as NodeJS) using proxy pass

My challenge involved proxy passing multipart/form-data through NextJS API routes, but the default built-in bodyParser was causing issues with incoming multipart data. Other plugins for NodeJS were also not allowing me to successfully proxy pass clear byte ...

Enhancing NextJS/playwrights with the latest nodejs upgrade?

I am facing issues with my Vercel build due to Playwright's outdated Node.js version: Error: Node.js version 12.x is deprecated. Starting from 2022-08-09, builds will fail unless the Node.js Version is set to 16.x in Project Settings. This change wa ...

I'm trying to establish a connection to MongoDB within the getStaticProps function in Next.js. Can anyone

Hello, I am a beginner in next.js and I have successfully rendered the home page on the server by populating the props object through a file named "products.json". Now, my next goal is to populate the props object in the function called getStaticProps usin ...

Troubleshooting error message: 'crypto' module not found while validating JWT token in Next.js middleware

While attempting to implement JWT verification for authentication with middleware, I encountered some errors that have proven difficult to resolve. ./node_modules/jwa/index.js:3:0 Module not found: Can't resolve 'crypto' Import trace for re ...

There was an error trying to read properties of undefined, specifically the 'prototype', in a code using Next.Js and Express

While attempting to incorporate express into my next.js project, I encountered errors when trying to initialize express: const express = require('express'); The errors that appeared were: Module not found: Can't resolve 'async_hooks ...

Tips for extracting and mapping a sub array from the category response JSON using SWR with MongoDB in a Next.js (Node.js) environment

Can anyone assist me with reading and mapping arrays inside JSON? Using Hook (useSWR / useCategories): import useSWR from "swr" const fetcher = (...args) => fetch(...args).then(res => res.json()) function useCategories () { const { data, erro ...

Next.js 14.0.4 is encountering an ENOENT error due to the absence of the BUILD_ID file

My Next.js 14.0.4 project is running into an ENOENT error due to the missing BUILD_ID file, here are some specifics about my project: Node.js version: 21.5.0 Next.js version: 14.0.4 [email protected] start next start ▲ Next.js 14.0.4 Local: ...

Having trouble with Firebase admin in your Next.js/Stripe webhook integration?

I've encountered an issue when using the stripe webhook in Next.js. Every time I attempt to set it up, I receive the following error: unable to detect a project id in this environment I initially tried setting it up in the app router and then trans ...

Troubleshooting a 400 error with the Stripe Webhook due to problems with the raw

After diligently following Stripes documentation on setting up webhooks and testing locally using their Stripe CLI, I have encountered a persistent issue. While I can successfully create events, I consistently receive a response of 400 POST. 2021-12-14 23: ...

What is the best way to utilize getInitialProps specifically during the building process of a NextJS site?

When I am developing a static site using NextJS, I need the getInitialProps method to run specifically during the build process and not when the client loads the page. During the build step, NextJS executes the getInitialProps method before generating the ...