Module 5 Summary
This lesson is a summary of the work we've done in Module 5.0.
📝 This module's quiz can be found - here.
🗒️ Solutions for this module's quiz can be found - here.
In this module, we build on top of the previous module to help conduct persistent login sessions in our application with the help of cookies 🍪.
Server Project#
src/index.ts
#
In the root src/index.ts
file of our server project, we import and use the cookie-parser
library as middleware to help populate req
's made to the server with an object keyed by the cookie names.
In our ApolloServer
constructor, we pass in the req
and res
objects for every request made as context to be accessible by all our GraphQL resolver functions.
require("dotenv").config();
import express, { Application } from "express";
import cookieParser from "cookie-parser";
import { ApolloServer } from "apollo-server-express";
import { connectDatabase } from "./database";
import { typeDefs, resolvers } from "./graphql";
const mount = async (app: Application) => {
const db = await connectDatabase();
app.use(cookieParser(process.env.SECRET));
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) => ({ db, req, res })
});
server.applyMiddleware({ app, path: "/api" });
app.listen(process.env.PORT);
console.log(`[app] : http://localhost:${process.env.PORT}`);
};
mount(express());
src/graphql/resolvers/Viewer/index.ts
#
In the viewerResolvers
map, we construct the options of the cookie we'll want to set with the help of the cookie-parser
library.
const cookieOptions = {
httpOnly: true,
sameSite: true,
signed: true,
secure: process.env.NODE_ENV === "development" ? false : true
};
In the utility logInViaGoogle()
function and once the user has successfully logged in, we set a new cookie labeled viewer
which is provided with the id
value of the user who has logged in. We introduce one other cookie option to state the maximum age of the cookie (i.e. the expiry time) is one year.
const logInViaGoogle = async ( res.cookie("viewer", userId, {
cookieOptions,
maxAge: 365 * 24 * 60 * 60 * 1000
});};
In our logIn()
mutation resolver, we call another utility function labeled logInViaCookie()
which is to be executed when the logIn
mutation is fired and an authorization code is not present as part of the mutation input.
This page is a preview of TinyHouse: A Fullstack React Masterclass with TypeScript and GraphQL - Part Two