Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware API cannot access blitzCtx or blitzResult from resolvers. #4003

Closed
raleigh9123 opened this issue Dec 9, 2022 · 1 comment
Closed
Labels
kind/bug Something isn't working status/done
Projects

Comments

@raleigh9123
Copy link

raleigh9123 commented Dec 9, 2022

What is the problem?

I encountered this problem trying to add additional information to the session object stored in my db when a user logs in. As a user logs in, I would like to take the user-agent values from the request, and add it to the 'session' value within the database so the user can see which devices and sessions have recently, or are actively being used to access that user's account.

I used the Blitz.js Middleware API, within my login.ts resolver to grab the user-agent value from the req param, then attach to the blitzCtx object that would then be passed to the resolver before logging in. However, the RequestMiddleware API does not seem to have the same definitions as stated in the docs according to a Typescript error. After doing a little digging, I found that the req and res params do not seem to matchup with the MiddlwareRequest and MiddlewareResponse types listed in the docs either (though the next param does correctly show the MiddlewareNext type). As such, the req param in the middleware function I wrote cannot access the blitzCtx object as it only seems to pass through the 'ServerResponse' type, as you might expect from a Connect/Express middleware function.
https://blitzjs.com/docs/middleware#middleware-api

An aside, I did try implementing the BlitzServerMiddleware function within the plugins array in my blitz-server.ts file, and everything worked correctly. I accessed the blitzCtx param from ctx param of my resolver function as expected. However, this is a global middleware that would then run upon every single query and mutation, which is not a behavior I would want for this application.
https://blitzjs.com/docs/middleware#blitz-server-middleware

I should note that I implemented something like this in a Blitz.js project prior to Blitz 2.0. The middleware api type was named Middleware then, and has been renamed to RequestMiddleware in Blitz 2.0.

I felt as if I was just making a silly error, but I can't seem to get a console log out of the MiddlewareAPI function. This worked with almost the exact same code in my last Blitz project, so I'm a little stumped.

Paste all your error logs here:

Typescript shows an error under

    res.blitzCtx.userAgent = req.headers["user-agent"]
Property 'blitzCtx' does not exist on type 'ServerResponse<IncomingMessage>'.  (ts2339)

Paste all relevant code snippets here:

login.ts

export const middleware: RequestMiddleware = async (req, res, next) => {
  res.blitzCtx.userAgent = req.headers["user-agent"]
  await next()
}

I also tried using the same function syntax I had used in my old project.

export const middleware: RequestMiddleware[] = [
  async (req, res, next) => {
    res.blitzCtx.userAgent = req.headers["user-agent"]
    await next()
  }
]

This is the code from the global middleware that I used and it seemed to work properly. I got the value I needed from the blitzCtx object within my mutation resolver.
blitz-server.ts

import { BlitzLogger, BlitzServerMiddleware } from "blitz"

export const { gSSP, gSP, api } = setupBlitzServer({
  plugins: [
    AuthServerPlugin({
      ...authConfig,
      storage: PrismaStorage(db),
      isAuthorized: simpleRolesIsAuthorized,
    }),
    BlitzServerMiddleware(
      async (req, res, next) => {
        res.blitzCtx.userAgent = req.headers["user-agent"]
        await next()
      }
    )
  ],
  logger: BlitzLogger({}),
})

What are detailed steps to reproduce this?

  1. Install a brand new Blitz.js project
  2. Add the above code snippet to your login.ts
  3. Try console logging the blitzCtx value from the ctx param within the mutation resolver. Returns undefined

Run blitz -v and paste the output here:

Blitz version: 2.0.0-beta.19 (global)
Blitz version: 2.0.0-beta.19 (local)
macOS Ventura | darwin-arm64 | Node: v18.10.0

Package manager: npm

System:
OS: macOS 13.0.1
CPU: (10) arm64 Apple M1 Max
Memory: 541.14 MB / 32.00 GB
Shell: 5.8.1 - /bin/zsh
Binaries:
Node: 18.10.0 - /opt/homebrew/bin/node
Yarn: 1.22.19 - /opt/homebrew/bin/yarn
npm: 8.19.2 - /opt/homebrew/bin/npm
npmPackages:
@blitzjs/auth: 2.0.0-beta.19 => 2.0.0-beta.19
@blitzjs/next: 2.0.0-beta.19 => 2.0.0-beta.19
@blitzjs/rpc: 2.0.0-beta.19 => 2.0.0-beta.19
@prisma/client: 4.6.0 => 4.6.0
blitz: 2.0.0-beta.19 => 2.0.0-beta.19
next: 12.2.5 => 12.2.5
prisma: 4.6.0 => 4.6.0
react: 18.2.0 => 18.2.0
react-dom: 18.2.0 => 18.2.0
typescript: ^4.8.4 => 4.9.3

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

No response

@raleigh9123 raleigh9123 added kind/bug Something isn't working status/triage labels Dec 9, 2022
@dillondotzip
Copy link
Member

Hey @raleigh9123

So originally we intentionally removed this from blitz 2.0, but I spoke to @flybayer and we're going to add middleware functionality back per resolver.

Regarding the documentation, some of the middleware stuff is the ghost from legacy blitz.

I will mark this issue as ready to work on for anyone who want's to tackle this.

@dillondotzip dillondotzip added the status/ready-to-work-on This issue is up for grabs label Dec 13, 2022
@blitzjs-bot blitzjs-bot added status/done and removed status/ready-to-work-on This issue is up for grabs labels Oct 24, 2023
@blitzjs-bot blitzjs-bot added this to Done in Toolkit Oct 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/bug Something isn't working status/done
Projects
Development

No branches or pull requests

4 participants