#middleware not working in nextjs
91 messages · Page 1 of 1 (latest)
🔎 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)
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
✅ 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)
@unkempt marsh A question, what If I want to pass some variables from my middleware to my page?
not possible
ok
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
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>
oh, right, thanks
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?
Are u using bcrypt?
yup
yes cookie or searchParam works
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
ok
works
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.
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
Also 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 is being used in db.ts, and imported to middleware..ts
sure
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
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}>
)
}
Ok, and is it safe to fetch in here?
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
its sending request to a external api
Any specific reasons?
Compelling reasons to replace Axios with the native Fetch API
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
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' })
with fetch, I get this warning, if I add custom values to headers:
can you show the code?
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
hmm try new Headers?
oh ok
"apiKey": ${process.env.MONGODB_API_KEY}
add `
"apiKey": `${process.env.MONGODB_API_KEY}`
it should work too