How to send cookies contain JWT from Apollo Server to web client?

Viewed 12

I'm currently working on backend server using ApolloServer framework. I want to send a JWT (for auth purpose) to the client's cookies.

How can I send cookies to the client app from my Apollo Server?


Here is my current source codes:

My apollo server project's trees:

Project Directories Tree

index.js :

import {ApolloServer} from "apollo-server";
import mongoose from "mongoose";
import dotenv from "dotenv";

import typeDefs from "./graphql/typeDefs/index.js";
import resolvers from "./graphql/resolvers/index.js";

dotenv.config();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({req}) => ({ req }),
});

const PORT = process.env.PORT;
const MONGODB = process.env.MONGODB;

mongoose.connect(MONGODB)
  .then(() => {
    console.log("Connected to MongoDB");
    return server.listen({port: PORT});
  })
  .then((res) => {
    console.log(`Yeaaayy!! Server is running at ${res.url} `);
  });

graphql/typeDefs/index.js :

import {gql} from "apollo-server";

const typeDefs = gql`
  type User {
    id: ID!
    username: String!
    email: String!
    role: String!
    isBanned: Boolean!
    fullName: String
    imgUrl: String
    about: String
    token: String
  }  


  type Mutation {
    login(usernameEmail: String!, password: String!): User!
  }
`;

export default typeDefs;

graphql/resolvers/index.js :

import authResolvers from "./authResolvers.js";

const resolvers = {
  Mutation: {
    ...authResolvers.Mutation,
  }
};

export default resolvers;

graphql/resolvers/authResolvers.js :

I want to implement this problem every time the login mutation requested/called by the client.

import {UserInputError} from "apollo-server";
import bcrypt from "bcryptjs";

import User from "../../models/User.js";

import {validateLoginInputs, validateRegisterInput} from "../../utils/validations/authValidations.js";
import {encryptPassword} from "../../utils/auth/auth-utils.js";
import {generateJWToken} from "../../utils/jwt/jwt-utils.js";

const authResolvers = {
  Mutation: {
    async login(_, {usernameEmail,password}){
      // Trim username/email
      usernameEmail = usernameEmail.trim();
      
      const {errors, valid} = validateLoginInputs({
        usernameEmail, password
      });
      if (!valid) throw new UserInputError('Error in login input(s)', {errors});
      
      try{
        const user = await User.findOne({$or:[{username: usernameEmail},{email: usernameEmail}]});
        if (!user) throw new UserInputError('User not found');
        
        const passwordMatch = await bcrypt.compare(password, user.password);
        if (!passwordMatch) throw new UserInputError('Wrong credentials');

        // About here I think I want to send my JWT to the client as a cookies
  
        return {
          ...user._doc,
          id: user._id,
          token: generateJWToken({
            id: user._id,
            username: user.username,
            email: user.email,
            role: user.role,
            isBanned: user.isBanned,
            fullName: user.fullName,
            imgUrl: user.imgUrl,
          }),
        };
      } catch (err) {
        throw err;
      }
    }
  }
};

export default authResolvers;

Any kind of help such as a solution, reference, article, etc. that possibly help to overcome this problem will be helpful, thanks.

0 Answers
Related