Next.js Discord

Discord Forum

middleware not working in nextjs

Answered
Anay-208 posted this in #help-forum
Open in Discord
Answered by Ray
move it under src/middleware.ts
View full answer

89 Replies

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']
}
- Attempted to access http://localhost:3000/dashboard/ ,
which I was able to
move it under src/middleware.ts
Answer
it need to be same level as app
@Ray it need to be same level as app
fixed by /dashboard/:path*
@Ray A question, what If I want to pass some variables from my middleware to my page?
ok
Northern Wheatear
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 @Ray
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>
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?
@Anay-208 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?
Northern Wheatear
Yep its not safe with cookies, user can modify. I think add some custom headers for this purpose. I would suggest the better way is to identify what kind (permission) of user it is directly in the server logic of that page
@Anay-208 yup
Northern Wheatear
@Northern Wheatear Check this https://github.com/kelektiv/node.bcrypt.js/issues/979
now i get this err
Server Error
ReferenceError: bcrypt is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Northern Wheatear
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
where do you use it? middleware?
@Ray where do you use it? middleware?
bcrypt is being used in db.ts, and imported to middleware..ts
bcrypt cannot be used in middleware
@Ray bcrypt cannot be used in middleware
more specifically, I'm importing a function in middleware.ts from db.ts. the specific function I'm importing doesn't use ts, however, other functions do
bcrypt relies on Node.js APIs not available in Next.js Middleware.
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?
no, 'use server' is for server action only
@Ray no, `'use server'` is for server action only
if I directly connect to the db in 'use server', it'll be exposed to the client?
routs.ts is processed on the server
or use a api, which has secret keys
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
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}>
  )
}
'use server' does nothing in here
it is server component by default
Ok, and is it safe to fetch in here?
yes
it is safe as long as no 'use client' on top
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
but it won't work if 'use client' is on top anyway
I'm using axios to send post request to my serverws
external server?
well, with nextjs. its better to use fetch
@Ray external server?
its sending request to a external api
@Ray well, with nextjs. its better to use fetch
Any specific reasons?
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
@Ray the result can be cached
and I don't want that
a session is supposed to expire after 30 mins
it's fine you can tell it to not cache
its up to you if axios works for you
I personally just use fetch
axios doesn't really work in middleware.ts, so i'll be using fetch. how can i tell that not to cache
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
oh didn't notice that code
thanks
@Ray ts const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
with fetch, I get this warning, if I add custom values to headers:
No overload matches this call.
can you show the code?
 await fetch('hr', {
    headers: {
      'x-header': '1'
    }
  })

like this?
@Ray ts await fetch('hr', { headers: { 'x-header': '1' } }) like this?
Yes, do I have to use new Headers?
new Headers({...headers})
it returns the same err
warning
@Ray can you show the code?
hmm try new Headers?
@Ray hmm try new Headers?
Still same warning
oh ok
"apiKey": ${process.env.MONGODB_API_KEY}
add `
"apiKey": `${process.env.MONGODB_API_KEY}`
oh ok, got it
I used
    "apiKey": process.env.MONGODB_API_KEY as string
it should work too
yup, it worked
if it could've said could be undefined, I could have fixed it
typescript like confuse people😆