1

I've created simple backend api using apollo-server-express and postgresql that has two mutations: register and login. When the login mutation is used, the api creates an auth token and a refresh token and then sends them as cookies using res.cookie(...). In the frontend, I'm using apollo-client to access my GraphQL api. When I call the login mutation, everything works as expected, I receive the set-cookie header along with the requested user-details. However, the cookies don't show up in the Application tab under Cookies. Can someone please help me. I'm using the following code: server/index.ts

import "dotenv/config";
import "reflect-metadata";
import * as express from "express";
import * as cors from "cors";
import {
  ConnectionOptions,
  createConnection,
  getConnectionOptions
} from "typeorm";
import { buildSchema } from "type-graphql";
import { GraphQLSchema } from "graphql";
import { ApolloServer } from "apollo-server-express";
import * as path from "path";
import * as cookieParser from "cookie-parser";

import {
  UserResolver,
  DepartmentResolver,
  CourseResolver,
  SubjectResolver,
  DocumentResolver
} from "./modules";
import { customAuthChecker, formatError, GQLRuntimeContext } from "./utils";

const getOptions = async () => {
  console.log(`NODE_ENV: ${process.env.NODE_ENV}`);
  let connectionOptions: ConnectionOptions;
  connectionOptions = {
    type: "postgres",
    synchronize: true,
    logging: false,
    entities: [path.join(__dirname, "./modules/**/*entity.*")]
  };
  if (process.env.DATABASE_URL) {
    Object.assign(connectionOptions, { url: process.env.DATABASE_URL });
  } else {
    // gets your default configuration
    // you could get a specific config by name getConnectionOptions('production')
    // or getConnectionOptions(process.env.NODE_ENV)
    connectionOptions = await getConnectionOptions();
  }

  return connectionOptions;
};

const connect = async (): Promise<void> => {
  const typeormconfig = await getOptions();
  console.log(`\n`);
  console.log(`\tconfiguration: `);
  console.log(typeormconfig);
  console.log(`\n`);
  await createConnection(typeormconfig);
};
connect().then(async () => {
  const schema: GraphQLSchema = await buildSchema({
    resolvers: [
      UserResolver,
      DepartmentResolver,
      CourseResolver,
      SubjectResolver,
      DocumentResolver
    ],
    authChecker: customAuthChecker
  });
  const app: express.Application = express();
  app.use(cookieParser());
  const server: ApolloServer = new ApolloServer({
    schema,
    formatError,
    context: ({ req, res }: GQLRuntimeContext): GQLRuntimeContext => ({
      req,
      res
    })
  });
  server.applyMiddleware({
    app,
    path: "/",
    cors: { origin: "*", credentials: true }
  });

  app.listen({ port: process.env.PORT || 4000 }, () => {
    console.log(
      ` Server ready at http://localhost:${process.env.PORT || 4000}${
        server.graphqlPath
      }`
    );
  });
});

client/index.tsx:

import React from "react";
import ReactDOM from "react-dom";
import {
  ApolloClient,
  ApolloProvider,
  NormalizedCacheObject,
  InMemoryCache
} from "@apollo/client";
import { createHttpLink } from "apollo-link-http";

import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

const link: any = createHttpLink({
  uri:
    /*process.env.NODE_ENV === "production"
      ? "https://the-notebook-graph.herokuapp.com/graphql"
  : */ "http://localhost:4000/graphql",
  credentials: "include"
});
const client: ApolloClient<NormalizedCacheObject> = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

ReactDOM.render(
  <ApolloProvider client={client}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </ApolloProvider>,
  document.getElementById("root")
);

serviceWorker.register();

Response headers in ReactJS application

Cookies after receiving the response

I get the following error when I try to use {...credentials: "include"...} in the frontend:

Unhandled Rejection (Error): Failed to fetch
Fardeen Panjwani
  • 491
  • 1
  • 4
  • 6

0 Answers0