How to handle cookies inside apollo-server-lambda

apollo-server-lambda subscriptions
apollo-server-lambda github
apollo-server-lambda typescript
apollo server set cookie
apollo-server forward headers
apollo-server cors
apollo server context
apollo-server response headers

set cookies inside a lambda serverless with apollo-server-lambda

I am migrating from apollo-server to the serverless version. Is there a way I can access the response object or another way to set cookies?

context: ({ event, context }) => ({
   headers: event.headers,
   functionName: context.functionName,

I was expecting in the context to have access to the res object like it was in the apollo-server.

I couldn't find a way to do that using apollo-server-lambda, so what a I did was use apollo-server-express and serverless-http in conjuction. The code below is using import/export because I am using typescript.

serverless-http accepts a variety of express-like frameworks.

import express from 'express'; // <-- IMPORTANT
import serverlessHttp from 'serverless-http'; // <-- IMPORTANT
import { ApolloServer } from 'apollo-server-express'; // <-- IMPORTANT
import typeDef from './typeDef';
import resolvers from './resolvers';

export const server = new ApolloServer({
    context: async ({ req, res }) => {
         * you can do anything here like check if req has a session,
         * check if the session is valid, etc...
        return {
            // things that it'll be available to the resolvers

const app = express(); // <-- IMPORTANT

server.applyMiddleware({ app }); // <-- IMPORTANT

// by the way, you can name the handler whatever you want
export const graphqlHandler = serverlessHttp(app, {
     * **** IMPORTANT ****
     * this request() function is important because 
     * it adds the lambda's event and context object 
     * into the express's req object so you can access
     * inside the resolvers or routes if your not using apollo
    request(req, event, context) { 
        req.event = event;
        req.context = context;

Now for instance you can use res.cookie() inside the resolver

import uuidv4 from 'uuid/v4';

export default async (parent, args, context) => {
// ... function code

const sessionID = uuidv4();

// a example of setting the cookie
context.res.cookie('session', sessionID, {
        httpOnly: true,
        secure: true,
        path: '/',
        maxAge: 1000 * 60 * 60 * 24 * 7,

another useful resource

Deploying with AWS Lambda - Apollo Server, This means they will vary for Express, Koa, Lambda, etc. This block of code is setting up a new GraphQL server, using Apollo Server 2.0. no public access to the schema or any fields, like an internal tool or maybe an independent simply pass through the headers or cookies to your REST endpoint and let it do the work . To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value. Example. Let us read cookies which we have set in previous example −

You can use the apollo-server-plugin-http-headers package.

Usage is as simple as this from within your resolvers:

    name: "cookieName",
    value: "cookieContent",
    options: {
        domain: "",
        expires: new Date("2021-01-01T00:00:00"),
        httpOnly: true,
        maxAge: 3600,
        path: "/",
        sameSite: true,
        secure: true

Authentication - Apollo Server, When I reload the page the initial page is rendered on server apps that don't use express? Currently using Lambda to handle requests� Before we get into figuring out user permissions, we have to figure out how to recognize a user first. From HTTP headers, to JSON web tokens, there are a number of ways to handle authentication of users, but once you have your user, controlling access looks pretty similar. We’ll be using a login token in an HTTP authorization header as an

You need a way to set the response headers in your resolvers.

What you can do is to set a value to the context object in your resolver.

const resolver = (parent, args, { context }) => {
  context.addHeaders = [{ key: 'customheader', value: 'headervalue'}]

You can catch the context in willSendResponse event in the server lifecycle by creating a Apollo Server plugin. You can then add your headers from customHeaders property to the GraphQLResponse object.

const customHeadersPlugin = {
  requestDidStart(requestContext) {
    return {
      willSendResponse(requestContext) {
        const {
          context: { addHeaders = [] }
        } = requestContext.context

        addHeaders.forEach(({ key, value }) => {
          requestContext.response.http.headers.append(key, value)

        return requestContext

You need to load the plugin in Apollo Server.

const server = new ApolloServer({
  plugins: [customHeadersPlugin],
  context: ({ context }) => ({

Now you've got a way to modify the response headers in your resolvers. To be able to set a cookie you can either set the Set-Cookie header manually with a cookie string or using a cookie library.

Thanks to Trevor Scheer of the Apollo GraphQL team for pointing me in the right direction when I needed to implement this myself.

Apollo request object missing cookies � Issue #1791 � apollographql , I am currently using nextJS with apollo and it's completely unusable for me together to host and review code, manage projects, and build software together. index.js server const cookieParser = require("cookie-parser"); this page to have SSR (and to be a lambda) for SEO purposes and remove Apollo Server Lambda slow performances I'm using Apollo Server Lambda to create some APIs hosted on AWS API Gateway and AWS Lambda. But what I noticed is that performances are really slow when the result has many fields.

Apollo Client does not pass cookies � Issue #4190 � apollographql , npm install express apollo-server-express cors bcrypt jsonwebtoken. Next, create an app.js file. In here, we're going to first handle the login process. The id and email values are now available inside our resolver(s). I am writing a graphql server component on AWS Lambda (NOT using graphql-server). On the client side I'm using apollo-client. On the response of the lambda function I'm setting const response =

How to authenticate using GraphQL Cookies and JWT, We'll implement this on an Apollo Server that uses Prisma as the ORM of There are several ways we can do this: via a cookie if you are strictly This file will handle whether a user is logged in or not when accessing a protected route. Inside decodedToken.js , we'll simply verify the token of the user� Try to enter the First Name and the Last Name and then click the submit button. This will display the first name and the last name on your screen and will also set two cookies firstName and lastName. These cookies will be passed back to the server when the next time you click the Submit button.

JWT authentication with Apollo Server 2: tips and tricks, I defined my Lambda integration in API Gateway using a stage variable. Why do I get an "Internal server error" and a 500 status code when I� There are some surprises that are more mild, like biting into a chocolate chip cookie only to discover it’s actually a raisin cookie. Your reaction will probably depend on how much you like or hate raisins, because no one loves raisins. I think everyone loves a surprise fudge filling inside an already flavorful and ridiculously soft cookie.

  • I had a lot of problems when trying to make both servers, Express and Lambda, work together with cookies using this method... the best solution was to remove cookies and sessions and use JWT
  • this is great, ty