Skip to content

docs: update Middleware API reference#30485

Merged
kodiakhq[bot] merged 1 commit intovercel:canaryfrom
balazsorban44:patch-1
Oct 27, 2021
Merged

docs: update Middleware API reference#30485
kodiakhq[bot] merged 1 commit intovercel:canaryfrom
balazsorban44:patch-1

Conversation

@balazsorban44
Copy link
Copy Markdown
Contributor

I changed the order of NextRequest and NextFetchEvent as they are presented in the function signature.

There also seemed to be some issues with the heading levels.

Also, NextResponse is a documented API, but the example code uses Response. I wasn't sure if this was a mistake in the docs or in the code.

I noticed that other similar docs pages have a collapsible Examples section at their top:

Image below:
image

Should the Middleware docs have the same?

@kodiakhq kodiakhq Bot merged commit 574651a into vercel:canary Oct 27, 2021
@styfle
Copy link
Copy Markdown
Contributor

styfle commented Oct 27, 2021

NextResponse is a documented API, but the example code uses Response

Both are acceptable return values. The NextResponse object has some helper methods on it.

We should definitely have examples linked from the Middleware docs to here: https://github.com/vercel/examples

@balazsorban44
Copy link
Copy Markdown
Contributor Author

Turns out Middleware is already kind of supported by next-auth

import { getToken } from "next-auth/jwt"
import { NextResponse } from "next/server"

export async function middleware(req) {
  // return early if url isn't supposed to be protected
  if (!req.url.includes("/protected-url")) {
    return NextResponse.next()
  }

  const session = await getToken({ req, secret: process.env.SECRET })
  // You could also check for any property on the session object,
  // like rolec === "admin" or name === "John Doe", etc.
  if (!session) return NextResponse.redirect("/api/auth/signin")

  // If user is authenticated, continue.
  return NextResponse.next()
}

What I would like is if we had a nicer API for this, and we also got the Database Session working. Again, I am not sure of the bottleneck effect there, since we have to do multiple database queries.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 27, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants