question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

middlewares - ReferenceError: self is not defined

See original GitHub issue

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #58~20.04.1-Ubuntu SMP Tue Jun 14 11:29:12 UTC 2022
Binaries:
  Node: 16.15.1
  npm: 8.1.2
  Yarn: 1.22.17
  pnpm: N/A
Relevant packages:
  next: 12.2.0
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0

What browser are you using? (if relevant)

Version 1.39.122 Chromium: 102.0.5005.115 (Official Build) (64-bit)

How are you deploying your application? (if relevant)

Docker

Describe the Bug

Ok I have two middlewares one inside the lib folder that wraps my API and another one inside pages

Note I follow https://nextjs.org/docs/messages/middleware-upgrade-guide maybe I am missing something

File src/middlewares/withAuth.tsx

import { JwtPayload, verify } from 'jsonwebtoken'
import { NextApiRequest, NextApiResponse } from 'next'

const jwtSecret = JSON.parse(process.env.AUTH_PRIVATE_KEY || ``)

export enum HASURA_ROLE {
  //ROLES
}
const getToken = (authHeader: string | undefined) => {
  if (typeof authHeader === 'undefined' || !authHeader) {
    return false
  }
  const token = authHeader.split(' ')[1]
  if (token) {
    return verify(token, jwtSecret.key, {
      algorithms: jwtSecret.type,
    })
  }
  return false
}
export default function withAuth(middleware: any, role: HASURA_ROLE) {
  // eslint-disable-next-line sonarjs/cognitive-complexity
  return (request: NextApiRequest, response: NextApiResponse): Promise<any> =>
    new Promise((resolve, reject) => {
      let isReject = false
      switch (role) {
// 
      }
      return isReject
        ? reject('You are not allowed to call endpoint')
        : middleware(request, response, (result: any) => async () => {
            return resolve(result)
          })
    })
}

example usage export default withAuth(tokenRegistry, HASURA_ROLE.WEBHOOK)

Another middleware inside pages src/pages/middleware.tsx

// middleware.ts
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
// https://nextjs.org/docs/messages/middleware-upgrade-guide
const PUBLIC_FILE = /\.(.*)$/

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function middleware(request: NextRequest) {
  const shouldHandleLocale =
    !PUBLIC_FILE.test(request.nextUrl.pathname) &&
    !request.nextUrl.pathname.includes('/api/') &&
    request.nextUrl.locale === 'default'

  return shouldHandleLocale
    ? NextResponse.redirect(`/en${request.nextUrl.href}`)
    : undefined
}

Error when running yarn run build nextjs/.next/server/pages/middleware.js:1:1) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions…js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.requirePage (/media/crypto-catalyst/Pytech/nextjs/node_modules/next/dist/server/require.js:61:12) at /nextjs/node_modules/next/dist/server/load-components.js:56:50 at processTicksAndRejections (node:internal/process/task_queues:96:5) { type: ‘ReferenceError’


### Expected Behavior

it should just work :-)

### Link to reproduction

/

### To Reproduce

Update to nextjs 12.2.0 

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

10reactions
marcusnunescommented, Jun 29, 2022

I have the same error over here.

// /pages/middleware.page.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  
  if (pathname.startsWith('/about')) {
    return NextResponse.redirect(new URL('/marcus', req.nextUrl));
  }
}

Middleware does not work at all and I get the same self is not defined error when I try to build.

PS: I’m using a custom pageExtensions.


FIXED Just moved the file from /src/pages/middleware.page.ts to /src/middleware.page.ts

5reactions
mattilohcommented, Jun 30, 2022

Thanks @marcusnunes. Actually it’s clearly stated in the migration guide and in the error message, I simply didn’t read carefully enough 🙈

CleanShot 2022-06-30 at 11 47 29@2x

Read more comments on GitHub >

github_iconTop Results From Across the Web

nextjs 12.2 middleware : ReferenceError: self is not defined
I am using a boilerplate with nextjs 12.2. I want to use the middleware so I added a middleware.ts in the page folder,...
Read more >
reactjs - Why am I getting ReferenceError: self is not defined ...
The error occurs because the library requires Web APIs to work, which are not available when Next.js pre-renders the page on the server-side ......
Read more >
self is not defined nextjs | The AI Search Engine You Control
I'm using filemanger in my Nextjs apps.it showing me ReferenceError: self is not defined. even though I disabled SSR on that page but...
Read more >
ReferenceError: self is not defined - Blockcerts Forum
This means that there is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it...
Read more >
Blog - Next.js 12.2
To update to the newest API changes for Middleware, please see the migration guide. Try Middleware for free on Vercel or when self-hosting...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found