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.

_middleware.js/.ts files being included in client-side bundles

See original GitHub issue

What version of Next.js are you using?

12.0.3

What version of Node.js are you using?

14.18.1

What browser are you using?

Chome

What operating system are you using?

OSX/Linux

How are you deploying your application?

firebase

Describe the Bug

When I attempt to use node packages intended for server-side use (i.e. ‘firebase-functions’) in my middleware, I get errors in the client pertaining to nodeJS native packages not being present.

When I do this, in the client when I load a page “blocked” by the defined middleware, I get the following error in the browser: Module not found: Can't resolve 'child_process'

This happens w/ other node packages intended for server-side use.

Expected Behavior

Should be able to use node packages in _middleware.js/.ts files since the understanding is that they’re only intended for server-side processing of requests.

To Reproduce

Create a _middleware.ts file somewhere.

import { NextFetchEvent, NextRequest, NextResponse } from 'next/server'
import { logger } from 'firebase-functions'
export const middleware = async (req: NextRequest, ev: NextFetchEvent) => {
  logger.info('hello world')
  return NextResponse.next()
}

Attempt to visit a page “blocked” by said middleware in the browser.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:8
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

7reactions
madhurjya-ackocommented, Nov 21, 2021

@RavenHursT Unfortunately, the next.js project assumes by default that all the _middlewares are being run on a limited env by default, even though I am not deploying them to vercel’s edge network. For my use case I wanted to create a basic authentication middleware using google-auth-library . I hope there is a way to run the middlewares in a full node.js runtime. Something like this inside each middleware would help:

export config = {
  runtime: 'native'
}
3reactions
RavenHursTcommented, Nov 20, 2021

@madhurjya-acko Yeah… well, AFAICT… that’s not entirely true. _middleware files only run in that limited env if you’re deploying to Vercel’s edge infrastructure.

Some discussion here on that: https://github.com/vercel/next.js/issues/30674#issuecomment-955788593

I’m actually trying to do the same thing as you are. Ultimately, I abandoned trying to use the new _middleware approach for verifying of firebase auth tokens.

What I did instead is I created an API endpoint in /pages/api/auth/verify.ts that takes an authorization header on the request and verifies the token there, returning 200 for valid tokens and 401 and 403 for missing or invalid tokens, respectively.

import * as authHeader from "auth-header"
import { NextApiRequest, NextApiResponse } from "next"
import admin from "firebase-admin"
import { StatusCodes, ReasonPhrases } from "http-status-codes"
import { initializeFirebaseAdminApp } from "../../../utils/api/init-firebase-admin-app"

const AUTH_BEARER_SCHEME = "Bearer"

const verify = async (req: NextApiRequest, res: NextApiResponse) => {
  initializeFirebaseAdminApp()
  const { headers: { authorization } = {} } = req

  const { scheme, token } = authHeader.parse(authorization)

  if (scheme !== AUTH_BEARER_SCHEME || !token) {
    res.status(StatusCodes.UNAUTHORIZED)
    return res.send(ReasonPhrases.UNAUTHORIZED)
  }

  try {
    const tokenInfo = await admin.auth().verifyIdToken(token)
    res.status(StatusCodes.OK)
    return res.json(tokenInfo)
  } catch {
    return res.status(StatusCodes.FORBIDDEN).send(ReasonPhrases.FORBIDDEN)
  }
}

export default verify

Then, for each page file that I needed to have gated by authentication, I just made the fetch request to that endpoint in a getServerSideProps, w/ the token for the user on the authorization header and handle the server-side redirect, using the redirect option in the returned GetServerSidePropsResult from getServerSideProps: https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

Sadly, _middleware doesn’t seem to be very useful in its limited form at this point. 😢

Read more comments on GitHub >

github_iconTop Results From Across the Web

The What, When, Why And How Of Next.js' New Middleware ...
A Middleware function can be at most 1MB, this includes all other code bundled with the function. Most use cases won't require such...
Read more >
Module not found: Can't resolve 'fs' in Next.js application
ts file. I was importing it like this, thanks to the autofill provided by VSCode. import {CUSTOM_TYPE} from ...
Read more >
Bundle and minify static assets in ASP.NET Core
Learn how to optimize static resources in an ASP.NET Core web application by applying bundling and minification techniques.
Read more >
Advanced Features: Output File Tracing - Next.js
For next build packages/web-app , packages/web-app would be the tracing root and any files outside of that folder will not be included. To...
Read more >
Build an API with Node.js, Express, and TypeScript - Split
The TypeScript code needs to be transpiled to JavaScript before the package is used in runtime. If someone were using your app as...
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