blitz-js / legacy-framework

MIT License
3 stars 2 forks source link

getCurrentUser query receiving undefined ctx.session on Cloud Run #314

Closed ajwgeek closed 2 years ago

ajwgeek commented 3 years ago

What is the problem?

My getCurrentUser query began receiving an undefined session in the 2nd parameter after upgrading to Blitz 0.40.0-canary.7. The starter app and docs seem to indicate that session shouldn't be undefined.

I cannot reproduce this on my local machine with blitz dev or blitz start, but it is occurring reliably in production on Cloud Run. It seems to also be occurring in Vercel, based on a very similar report in this thread on the Blitz.js Discord.

I use a Dockerfile to deploy to Cloud Run which I have summarized below. I have also included the relevant sections of my blitz.config.ts file, Ctx type, and getCurrentUser queries.

Paste all your error logs here:

Blitz CLI

23:24:57.253 INFO getCurrentUser() Starting with input: null 
23:24:57.255 ERROR getCurrentUser() 
 TypeError  Cannot read property 'userId' of undefined
error stack:
• api-utils.ts:207 <anonymous>
    node_modules/next/server/api-utils.ts:207:30

• middleware.ts:130 dispatch
    node_modules/next/server/middleware.ts:130:32

• auth-sessions.ts:198 <anonymous>
    node_modules/next/stdlib-server/auth-sessions.ts:198:12

• auth-sessions.js:21 asyncGeneratorStep
    node_modules/next/dist/stdlib-server/auth-sessions.js:21:28

• auth-sessions.js:39 _next
    node_modules/next/dist/stdlib-server/auth-sessions.js:39:17

• task_queues:96 processTicksAndRejections
    node:internal/process/task_queues:96:5

Browser Console

react-dom.development.js?61bb:66 Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot
react_devtools_backend.js:2850 Error: Cannot read property 'userId' of undefined
useBaseQuery.js?e893:91 Uncaught Error: Cannot read property 'userId' of undefined

Paste all relevant code snippets here:

getCurrentUser.ts

import { Ctx } from "blitz";
import prisma from "db";
export default async (_query: unknown, { session }: Ctx) => {
    // console.log(session) prints undefined
    // The line below throws an error in production, because session is undefined.
    if (session.userId) {
        return prisma.user.findUnique({
            select: {
                email: true,
                id: true,
                role: true,
            },
            where: {
                id: session.userId,
            },
        });
    }
    return null;
};

types.ts

declare module "blitz" {
    export interface Ctx extends DefaultCtx {
        session: SessionContext;
    }
}

Dockerfile

# Stage 1. Builder
FROM node:current AS builder

WORKDIR /app
COPY . .

RUN npm install && blitz build

# @see https://cloud.google.com/build/docs/build-config#dir
RUN mkdir -p /workspace && mv .next/ node_modules/ /workspace

# Stage 2. Production Image
FROM node:current

WORKDIR /workspace
RUN mkdir -p /app && mv .next/ node_modules/ /app

WORKDIR /app
COPY . .

RUN npm install --production
CMD ["npm", "run", "start"]

blitz.config.js

        sessionMiddleware({
            createSession: async (data) => {
                let user;
                if (data.userId) {
                    user = {
                        connect: {
                            id: data.userId,
                        },
                    };
                }

                return prisma.session.create({
                    data: {
                        ...data,
                        user,
                        userId: undefined,
                    },
                });
            },
            deleteSession: async (handle) =>
                prisma.session.delete({
                    where: {
                        handle,
                    },
                }),
            getSession: async (handle) =>
                prisma.session.findUnique({
                    where: {
                        handle,
                    },
                }),
            getSessions: async (userId) =>
                prisma.session.findMany({
                    where: {
                        userId,
                    },
                }),
            isAuthorized: simpleRolesIsAuthorized,
            sessionExpiryMinutes: process.env.SESSION_EXPIRY_MINUTES,
            updateSession: async (handle, data) =>
                prisma.session.update({
                    data,
                    where: {
                        handle,
                    },
                }),

What are detailed steps to reproduce this?

  1. Create an app on Blitz 0.40.0-canary.7.
  2. Use a Dockerfile to build and deploy to Cloud Run. This issue also seems to occur on Vercel, as noted above.
  3. Execute the getCurrentUser query using the useCurrentUser hook. These are included in the Blitz.js starter app.
  4. You will be redirected to the 500 error page with the following message: "Cannot read property 'userId' of undefined.". In addition, the logs pasted above should be reproduced in the browser console and Blitz CLI.

Run blitz -v and paste the output here:

Linux 5.4 | linux-x64 | Node: v16.6.1

blitz: 0.40.0-canary.7 (global)
blitz: 0.40.0-canary.7 (local)

  Package manager: npm 
  System:
    OS: Linux 5.4 Debian GNU/Linux 10 (buster) 10 (buster)
    CPU: (4) x64 Intel(R) Xeon(R) Platinum 8168 CPU @ 2.70GHz
    Memory: 1.42 GB / 7.78 GB
    Shell: 5.0.3 - /bin/bash
  Binaries:
    Node: 16.6.1 - /usr/local/bin/node
    Yarn: 1.22.5 - /usr/bin/yarn
    npm: 7.20.3 - /usr/local/bin/npm
    Watchman: Not Found
  npmPackages:
    @prisma/client: ^2.25.0 => 2.27.0 
    blitz: ^0.40.0-canary.7 => 0.40.0-canary.7 
    prisma: ^2.25.0 => 2.27.0 
    react: alpha => 18.0.0-alpha-b6ff9ad16-20210820 
    react-dom: alpha => 18.0.0-alpha-b6ff9ad16-20210820 
    typescript: ~4.3.2 => 4.3.5 

Please include below any other applicable logs and screenshots that show your problem:

No response

flybayer commented 3 years ago

Sweet, thanks! I'll look into it

flybayer commented 2 years ago

Fixed in https://github.com/blitz-js/blitz/pull/2730