How to access custom parameters set in middleware in Next.js server actions?

I'm currently utilizing middleware.ts to intercept and authenticate user requests. However, I want to include data from our database in these authenticated requests.

Within my server action code, the structure is as follows:

export async function getProjectsByUser(): Promise<PrismaProject[]> {
  const user = await getUser()
  const projects = await prisma.project.findMany({
    where: {
      user_id: user.id,
    },
    include: {
      Document: true,
      Conversation: {
        include: {
          Message: true,  
        },
      },
    },
  });

  return projects
}

The initial line within this function fetches the user. Although, ideally, I would prefer to retrieve this information from the middleware instead. Unfortunately, I am uncertain how to achieve this. Are there any recommended best practices for referencing user information in middleware?

Answer №1

If you want to retrieve the data stored in your middleware within your route controller, you can simply attach it to the req object. Middleware has the ability to add properties and values to the req object, making them accessible to the route controller.

// middleware.ts
export async function authenticateUser(req, res, next) {
  const user = await getUser(); 
  // implementation
  req.user = user;
  next();
}

You can then access the user data from the req object.

export async function getProjectsByUser(req: Request, res: Response) {
  const user = req.user;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use TailwindCSS in NextJS to remove the "gap" className from a component?

Currently, I am working on button components in NextJS with Tailwindcss and I am encountering a problem with some variants. Everything works fine, except when I remove the children (button text), I notice something strange that I can't quite figure ou ...

Using interpolation brackets in Angular2 for variables instead of dots

I'm curious if Angular2 has a feature similar to the bracket notation in Javascript that allows you to use variables to select an object property, or if there is another method to achieve the same functionality. Here is the code snippet for reference ...

Typescript's default string types offer a versatile approach to defining string values

Here is an example code snippet to consider: type PredefinedStrings = 'test' | 'otherTest'; interface MyObject { type: string | PredefinedStrings; } The interface MyObject has a single property called type, which can be one of the ...

The FlatList glides effortlessly in any direction

My FlatList allows me to drag and move it in all directions (up/down/right/left) even though it appears vertically due to styling. The scroll bar still shows horizontally, which I want to disable. How can I achieve this? This is the code snippet for using ...

Error: TypeError encountered during UI Runtime JSON conversion of Circular Data Structure

I'm facing an issue while attempting to parse and stringify certain JSON data. The error occurs on this specific line of code: this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns))); Below is the complete @Input (using Ang ...

Troubles encountered while trying to dispatch an action in an Angular ngrx unit test

I have a situation where a component is fetching data from an API, but the data is only needed once, so I have opted not to use a reducer and selector for it. Instead, I am using actions and effects to handle the API call. Here is the code I am trying to ...

Is it possible to retrieve data in Next.js using an asynchronous function while also utilizing state?

Good day! I have a question about my Next.js 13 project. I'm currently working on an e-commerce site using Sanity.io as the CMS. The issue I'm facing is that I want to fetch data with an async function but also use the "useState" hook from React ...

Why does React useRef function smoothly in development but encounter errors in production?

The function "header" is using the React Hook called "useRef", but it is neither a React function component nor a custom React Hook function. Remember, React component names should start with an uppercase letter and React Hook names should start with the ...

Issues with Popover Trigger in React when using Chakra UI

https://i.sstatic.net/FTQ4r.png Whenever I click on this profile component, the popover should be triggered. However, when wrapping the children of <PopoverTrigger>...code</Popovertrigger> in <PopoverTrigger><ProfileComponent/>< ...

The console logs generated by the Next-auth authorization function are not appearing in either the terminal or the browser console

Why can't I find the console statement from the Credential Provider's authorize function after signing in on my custom login page? It doesn't show up in the Browser Console or Terminal. Help :( const onSubmit = async (e) => { e.preven ...

The issue with NextJS routing occurs when switching between pages and the incorrect file is being attempted to be opened

My Desire I wish to smoothly transition between pages without encountering any errors. The Issue at Hand An unusual routing problem is causing trouble for me. Here's a glimpse of my folder structure: pages [app] [object] index.js ind ...

`I am encountering an issue with retrieving the session in nextAuth`

While trying to learn nextAuth from tutorial videos on YouTube, I encountered an issue. Here is my app/api/auth/[...nextauth].js file import NextAuth from "next-auth"; export default NextAuth({ providers: [ CredentialsProvider({ name: ...

What steps should I take to establish a one-to-one relationship with legacy tables?

As I work on developing a web application (angular, nestjs, typeorm), I am faced with the challenge of linking two legacy user tables together within our existing system. Despite my efforts, I continue to encounter an error message related to column refere ...

Is it possible to detach keyboard events from mat-chip components?

Is there a way to allow editing of content within a mat-chip component? The process seems simple in HTML: <mat-chip contenteditable="true">Editable content</mat-chip> Check out the StackBlitz demo here While you can edit the content within ...

What is the process for incorporating styles into an external widget?

I am currently navigating my way through NextJS and attempting to incorporate a bespoke stylesheet into my code using a third-party widget. Unfortunately, I have hit a roadblock in this process. The names I have assigned to the style sheet align with what ...

Change the http observable response to an array that can be used with ngFor

My goal is to dynamically load select options based on an API response, using observables in Angular 5 for HTTP requests. However, when trying to parse the response into select options, I encountered the following error: Cannot find a differ supporting o ...

ng-click not triggering the typeScript function

I am encountering an issue while integrating my AngularJS code with TypeScript as my ng-click function is not functioning properly. Below is my controller code: module CustomerSearch.controllers { export class CustomerCtrl { static $inject = [ ...

The TN-Models-FP error message states that it is not allowed to use the `create` model without an associated `entity` model

Utilizing the TN-models-fp library to construct a basic api inspired by the provided examples, here is my implementation in api.ts: import { axios } from '../axios-instance' import { createApi } from '@thinknimble/tn-models-fp' import { ...

Adjusting the position of Angular Mat-Badge in Chrome browser

I'm currently using the newest version of Angular and I am attempting to utilize the Angular materials mat-badge feature to show the number of touchdowns a player has thrown. However, in Chrome, the badge position seems to shift when the number is inc ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...