#Import Protection / Middlewares

12 messages · Page 1 of 1 (latest)

icy atlas
#

Shouldn't the createMiddleware() function be declared in files named **/*.server.* and **/server/** just as it is in createServerFn(), since they are isomorphic?

feedback that a maintainer provided regarding serverFn + imports: #1479516645733957774 message

I'm separating my code into client and server parts, and the following import isn't working

// @/server/auth/middleware.ts
import { createMiddleware } from '@tanstack/react-start'
import {
  setResponseHeader,
  setResponseStatus,
} from '@tanstack/react-start/server'
import { auth } from '@/server/auth/auth'

export const authMiddleware = createMiddleware().server(
  async ({ next, request }) => {
    const headers = request.headers
    const session = await auth.api.getSession({
      headers,
      query: { disableCookieCache: true },
      returnHeaders: true,
    })

    // Forward any Set-Cookie headers to the client, e.g. for session/cache refresh
    // ..... 

    return next({
      context: {
        user: session.response.user,
        orgId: organizationId,
      },
    })
  },
)

import { authMiddleware } from '@/server/auth/middleware' is not possible 👇👇

// @/utils/organization/organization.functions.ts
import { createServerFn } from '@tanstack/react-start'
import { listUserOrganizationsDetailedServer } from './organization.server'
import { authMiddleware } from '@/server/auth/middleware' // That causes an import error

export const getUserOrganizationsDetailed = createServerFn({
  method: 'GET',
})
  .middleware([authMiddleware])
  .handler(async ({ context }) => {
    return await listUserOrganizationsDetailedServer(context.user.id)
  })
sly seal
#

please provide a complete minimal reproducer project as a git repo

icy atlas
#

Just run the project with pnpm run dev.

  1. It will display a route that makes a request to get the todos from the serverFn - There's a button on the screen to make the request.

  2. The server function uses middleware with the '.server.ts' extension. If you enable behavior: 'error' in vite.config.ts, it will display a reproducible error on the screen.

sly seal
#

this project is not showing a problematic behavior

#

you placed a middleware inside a .server.ts file

#

and thus it errors

#

middleware is isomorphic so can be imported on the client

icy atlas
sly seal
#

your original code looked different, what was the problem here?

icy atlas
sly seal
#

so? all good now?