Middleware doesn't load the `server.mjs` variables

I have the followinng middleware in src/middleware.ts
import {NextRequest, NextResponse} from 'next/server'
import {env} from 'src/env/server.mjs'

// This function can be marked `async` if using `await` inside
export function middleware(req: NextRequest) {
if (!['_next', 'favicon.icon', 'assets'].some(c => req.nextUrl.pathname.includes(c))) {
console.info('Match the path', req.url, req.nextUrl.pathname)
}

return NextResponse.next()
}

// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/',
'/((?!api|_next/static|_next/image|favicon.ico).*)',
'/((?!users/login|users/register|users/forgot|users/activation|users/register).*)',
],

}
import {NextRequest, NextResponse} from 'next/server'
import {env} from 'src/env/server.mjs'

// This function can be marked `async` if using `await` inside
export function middleware(req: NextRequest) {
if (!['_next', 'favicon.icon', 'assets'].some(c => req.nextUrl.pathname.includes(c))) {
console.info('Match the path', req.url, req.nextUrl.pathname)
}

return NextResponse.next()
}

// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/',
'/((?!api|_next/static|_next/image|favicon.ico).*)',
'/((?!users/login|users/register|users/forgot|users/activation|users/register).*)',
],

}
But i get the zod error because the serverSchema fails the parse.
❌ Invalid environment variables:
DATABASE_URL: Required
NODE_ENV: Required
❌ Invalid environment variables:
DATABASE_URL: Required
NODE_ENV: Required
4 Replies
Finn
Finn2y ago
Run cp .env.example .env Or set the above environment variables manually
cje
cje2y ago
i just tested this and it worked:
// src/middleware.ts
import { env } from "./env.mjs";

export const middleware = () => {
console.log("in middleware");
const nextAuthUrl = env.NEXTAUTH_URL;
console.log(nextAuthUrl); // works
};

export const config = {
matcher: ["/"],
};
// src/middleware.ts
import { env } from "./env.mjs";

export const middleware = () => {
console.log("in middleware");
const nextAuthUrl = env.NEXTAUTH_URL;
console.log(nextAuthUrl); // works
};

export const config = {
matcher: ["/"],
};
it's possible that typesafe env vars were broken in middleware in an old ct3a version if that's the case, maybe copy the new env var setup into your existing app
Finn
Finn2y ago
Oh wait I think your right I had that a month back I think.
Lautaro_dapin
Lautaro_dapinOP2y ago
i will try that, i create this project 2 weeks ago idk how much it changed thanks @cje it was the old env version for the project I had the env folder with the schema server and client I removed it and coopy the new env.mjs into the /src folder and it work perfectly
Want results from more Discord servers?
Add your server