#middleware not working in nextjs

91 messages · Page 1 of 1 (latest)

shell delta
iron notchBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

shell delta
#

Here are my steps I did:

  • Create middleware.ts in app folder
#
  • Add the following contents:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/login', request.url))
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: ['/dashboard/*', '/dashboard']
}
unkempt marsh
#

move it under src/middleware.ts

#

it need to be same level as app

shell delta
#

fixed by /dashboard/:path*

iron notchBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1180863390625841213 message)

shell delta
#

@unkempt marsh A question, what If I want to pass some variables from my middleware to my page?

shell delta
#

ok

marsh lagoon
#

Hey but if you need to pass some value to your page from middleware to your page you can set some custom cookies in the middleware and get them in your page

#

That works I think. Could you correct me if I'm wrong @unkempt marsh

shell delta
#

I'm getting this error

./node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <!doctype html>
| <html>
| <head>
shell delta
#

so heres how it works.
There are all the permissions, which middleware will fetch and keep it in the cookies, then can't the user modify it?

shell delta
unkempt marsh
marsh lagoon
marsh lagoon
shell delta
marsh lagoon
#

Hey can you try this. I'm not sure this works because I haven't tried it yet

#

Try this for your next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental:{
    serverComponentsExternalPackages: ['bcrypt'],
  }
}

module.exports = nextConfig
unkempt marsh
#

where do you use it? middleware?

shell delta
unkempt marsh
#

bcrypt cannot be used in middleware

shell delta
unkempt marsh
#

bcrypt relies on Node.js APIs not available in Next.js Middleware.

shell delta
#

ok, i guess I know how to fix this now

#

A question. wherever I use route.ts, or "use server", all the stuff is processed in the server, right?

unkempt marsh
#

no, 'use server' is for server action only

shell delta
unkempt marsh
#

routs.ts is processed on the server

shell delta
#

or use a api, which has secret keys

unkempt marsh
#

it may expose it if you call it in client component

#

with server component, you can just fetch the data in it. and pass the data to client component if needed

shell delta
#

I'm talking like this

"use server";



export default function Home({searchParams}: {searchParams?: any}) {
const data = await (await fetch(...url)).json()
  return (
   <OtherComponent data={data}>
  )
}

unkempt marsh
#

'use server' does nothing in here

#

it is server component by default

shell delta
#

Ok, and is it safe to fetch in here?

unkempt marsh
#

yes

#

it is safe as long as no 'use client' on top

shell delta
#

ok, and I'm getting this error in middleware.ts:

AxiosError: There is no suitable adapter to dispatch the request since :
- adapter xhr is not supported by the environment
- adapter http is not available in the build
unkempt marsh
#

but it won't work if 'use client' is on top anyway

shell delta
#

I'm using axios to send post request to my serverws

unkempt marsh
#

external server?

unkempt marsh
#

well, with nextjs. its better to use fetch

shell delta
shell delta
unkempt marsh
#
export default async function Page() {
  // This request should be cached until manually invalidated.
  // Similar to `getStaticProps`.
  // `force-cache` is the default and can be omitted.
  const staticData = await fetch(`https://...`, { cache: 'force-cache' })
 
  // This request should be refetched on every request.
  // Similar to `getServerSideProps`.
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
 
  // This request should be cached with a lifetime of 10 seconds.
  // Similar to `getStaticProps` with the `revalidate` option.
  const revalidatedData = await fetch(`https://...`, {
    next: { revalidate: 10 },
  })
 
  return <div>...</div>
}
#

the result can be cached

shell delta
#

a session is supposed to expire after 30 mins

unkempt marsh
#

it's fine you can tell it to not cache

#

its up to you if axios works for you

#

I personally just use fetch

shell delta
#

axios doesn't really work in middleware.ts, so i'll be using fetch. how can i tell that not to cache

unkempt marsh
#
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
shell delta
#

oh didn't notice that code

#

thanks

shell delta
unkempt marsh
#

can you show the code?

#
 await fetch('hr', {
    headers: {
      'x-header': '1'
    }
  })

like this?

shell delta
#

new Headers({...headers})

#

it returns the same err

#

warning

shell delta
unkempt marsh
#

hmm try new Headers?

shell delta
unkempt marsh
#

oh ok

#

"apiKey": ${process.env.MONGODB_API_KEY}

#

add `

#
"apiKey": `${process.env.MONGODB_API_KEY}`
shell delta
#

oh ok, got it

#

I used

    "apiKey": process.env.MONGODB_API_KEY as string
unkempt marsh
#

it should work too

shell delta
#

yup, it worked

#

if it could've said could be undefined, I could have fixed it