middleware not working in nextjs
Answered
Anay-208 posted this in #help-forum
89 Replies
- 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
which I was able to
move it under
src/middleware.tsAnswer
it need to be same level as app
fixed by /dashboard/:path*
Anay-208OP
@Ray A question, what If I want to pass some variables from my middleware to my page?
Anay-208OP
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
Anay-208OP
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?
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
Anay-208OP
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 = nextConfigAlso you can read https://nextjs.org/docs/app/api-reference/next-config-js/serverComponentsExternalPackages for more context what this does
where do you use it? middleware?
bcrypt cannot be used in middleware
@Ray bcrypt cannot be used in middleware
Anay-208OP
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.
Anay-208OP
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
Anay-208OP
if I directly connect to the db in 'use server', it'll be exposed to the client?
routs.ts is processed on the server
Anay-208OP
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
Anay-208OP
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 hereit is server component by default
Anay-208OP
Ok, and is it safe to fetch in here?
yes
it is safe as long as no '
use client' on topAnay-208OP
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 buildbut it won't work if
'use client' is on top anywayAnay-208OP
I'm using axios to send post request to my serverws
external server?
well, with nextjs. its better to use fetch
@Ray external server?
Anay-208OP
its sending request to a external api
@Ray well, with nextjs. its better to use fetch
Anay-208OP
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
Anay-208OP
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
Anay-208OP
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' })Anay-208OP
oh didn't notice that code
thanks
@Ray ts
const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
Anay-208OP
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?
Anay-208OP
Yes, do I have to use new Headers?
new Headers({...headers})it returns the same err
warning
hmm try new Headers?
@Ray hmm try new Headers?
Anay-208OP
Still same warning
Anay-208OP
oh ok, got it
I used
"apiKey": process.env.MONGODB_API_KEY as stringit should work too
Anay-208OP
yup, it worked
if it could've said could be undefined, I could have fixed it
typescript like confuse people😆