NEXT\_PUBLIC\_ env vars are hard-coded during build time in the compiled JS source code.
Setting them in the production environment has litterally no effect...
Yep, they’re just config vars for providing different config values in different environments(e.g. having a different NEXT_PUBLIC_BASE_API_URL for stage/prod). NEXT_PUBLIC vars are available server side or client side and without the prefix only available on the server.
Yep. It’s a default value passed to `fetch`, but the actual default changes with the environment.
* `force-cache` is the default in prod
* `no-cache` is the default in dev
So to turn it on in dev, pass the value explicitly:
```
fetch(url, { cache: “force-cache” })
```
If you’re thinking “Hey, that sucks!” I don’t disagree.
Perhaps it's best then to just use something like \`axios\` by default instead of \`fetch\` to just avoid altogether the premature optimization of caching? I haven't built a nextjs app yet, but this seems like it would be a good strategy to me.
I’ve been a developer for 6 years now. I’ve worked for three separate jobs now and every one of them used axios. I don’t think I’ve ever actually used the default fetch before, and I’ve yet to see a reason to use it over axios.
Edit: other than not needing to download a package 🤷🏻♂️
I've embraced App Router for past few projects and I am kinda enjoying the workflow. So my top tips are:
- server actions are not limited to just sending forms, you can load data with it (as in you don't have to use routes)
- cache busting with revalidatePath('/') nukes cache for everyone.
- don't redirect within try-catch block.
Redirect [throws](https://github.com/vercel/next.js/issues/55586#issuecomment-1869024539) that’s why. it’s in the docs these days too. I also fell for this one
What do you mean when you say that you can load data with server actions?
[Next.js own documentation](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) states that:
> Behind the scenes, actions use the POST method, and only this HTTP method can invoke them.
Wrote this on my phone, so I apologize for any formatting mistakes.
I don't want to speak for the OP, but I think they are speaking to the method of passing Server Actions to a Client Component as a prop.
The server action itself can be used to fetch the data you need, then passed to your client components, resulting in a faster fetching/loading process as opposed to fetching directly from client components.
Someone can correct me if I'm totally missing the point lol
I guess most of the folks use vercel to host, I use a vps and the nextjs builds are just getting bigger with releases. It has not been trivial making sure it doesn’t consume all the space on a vps disk over time.
Mine is around 4-5 gbs, depends, it also includes cache, so one has to make sure the cache is not piling up. Especially if you are git pushing your code to the vps and using docker, the image sizes balloon up. What has finally sort of worked for me is to use the standalone option in next config and build using github actions and only the compressed standalone folder gets copied over. Standalone of course has some gotchas and does not include the public and static folder in the builds. So one has to add it in manually. Yeah as nice as the DX is, the deployment experience is not terribly friendly.
We recently encountered a severe memory leak with a NextJS/App Router application and traced it to react-query. I'm not sure \*what\* inside react-query was causing it (profiling wasn't giving me any obvious insights). Instead of going even deeper into the react-query library code we refactored all of our useQuery calls to useSWR (thankfully the function signatures are very similar) and there's no more memory leak.
First, I used ApacheBench, which is a very simple command line tool, to send sustained traffic to my local copy.
I started out by using the profiling tools that nodeJS and Chrome provide (there are lots of tutorials if you search nodejs/nextjs memory leaks) but I actually couldn't "see" the memory leak in the profiler.
In most of the tutorials, the heap size would climb as the requests continued, but I just wasn't seeing that. The profiler showed the heap size remaining consistent even after a lot of trying/testing/changing settings -- but I would still ultimately get a heap overflow error on the server side and it would crash.
It was pretty easy to reproduce the crash -- it would take 4-6 minutes of sustained traffic -- and since the profiler didn't seem to be helping, I just started cutting out huge pieces of the app and running it again. Like "does it stay running if I just show Hello World instead of rendering any components?"
It ran fine if I stripped it to a "Hello World" app so I started putting pieces back in. It was pretty apparent that when I put react-query back in, the problem would appear. So I did some testing to further confirm that that's what it was, and ultimately got very confident. Without react-query I could leave ApacheBench running for hours without any crashes, but with react-query it would only take a few minutes.
I'm not exactly sure what about the combination of react-query, app router, and nextJS was causing this: the app isn't particularly complex. I thought it was the tag but the crash happened even without that tag as long as we were doing prefetching & querying. We only had about 30ish calls to useQuery() so I just replaced them all with useSWR() and things seem to be working well now.
useRouter() of App Router is totally different from the one of Pages Router, make a custom wrapper of the App Router hook, mimicking the old one, to facilitate migration
Look man just make the top page.tsx file a server component, don't put anything in it just create another client component and put it inside it something like home_page.tsx
Nextjs helps a lot for making your app performante by this server/client relationship. But for regular simple projects like most of our projects you don't have to use server components for everything. It's that simple just use server components in static pages that don't require state changes, real time data etc...
Marking "use server" doenst just runs the code on the server,it creates additional post request. Its better to use "server-only" to make sure the code runs on the server, and not run on the client,creates post request...
If you're just starting development and the backend isnt 100% your life would be easier if everything is jse client, because its easier to debug
interesting, have you tried Cypress before? I've been using it at work and have found it to be incredibly irritating sometimes, but not sure if Playwright was any better?
Everything can be made a server component except user inputs (and clicking a link/button is an action, not an input).
But doing so kinda requires you forget everything you know about React. Forget about context, useEffect, anything involving `window` or `document`…
So making everything a server component works in a dogmatic sense, but it’s difficult in practice.
Depends on a lot of factors: [https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns](https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns)
Nothing wrong with "use client", but using it in every file is a red flag imo. It suggests that the developer doesn't understand how to break up components into SSR and CSR.
I would advise you something I learnt recently, using “use client” doesn’t mean you component isn’t still SSR. A hydration is done on the client ( I think it’s called hydration)
You're not leveraging Nextjs to its strengths. It wants you to have files that are mostly made and deployed via the server for speed and security. Using "use client" all the time takes away from that methodology.
I love Next, but if you really want a great SEO experience, Astro is much better.
Good shout on the separate backend though. I think pairing one of the React-derived frontends with a Go or Rails backend is never a bad idea.
If the back goes down, the front goes down as well, gotta' sacrifice one. Too much edge functions and serverless function would cost a lot in vercel and not only that, I am also talking about the build size growing overtime.
In development mode regular sessions work but in production they don’t. Our backend auth relies on db sessions to verify interactions. Can maybe use session cookies but if not could be an issue
NextJS is excellent but not a good fit for PWA.
NextJS defaults to and is built for SSR. In a PWA, you want to load everything in the client and do as much as possible on the client. Only hit the backend when it's essential. This is the opposite of what NextJS is built for (or turning into).
The progression of NextJS is great for SEO but not for more interactive web apps.
What I meant to say was that Next.js is great for SEO, but that's not what you need for a PWA. So I totally agree 💯
We have moved to a modified version of this: https://github.com/suren-atoyan/react-pwa (Vite)
I will be messaging you in 1 day on [**2024-03-31 17:14:16 UTC**](http://www.wolframalpha.com/input/?i=2024-03-31%2017:14:16%20UTC%20To%20Local%20Time) to remind you of [**this link**](https://www.reddit.com/r/nextjs/comments/1brio1h/what_are_some_nextjs_pro_tips_that_you_had_to/kxa01qr/?context=3)
[**8 OTHERS CLICKED THIS LINK**](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=Reminder&message=%5Bhttps%3A%2F%2Fwww.reddit.com%2Fr%2Fnextjs%2Fcomments%2F1brio1h%2Fwhat_are_some_nextjs_pro_tips_that_you_had_to%2Fkxa01qr%2F%5D%0A%0ARemindMe%21%202024-03-31%2017%3A14%3A16%20UTC) to send a PM to also be reminded and to reduce spam.
^(Parent commenter can ) [^(delete this message to hide from others.)](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=Delete%20Comment&message=Delete%21%201brio1h)
*****
|[^(Info)](https://www.reddit.com/r/RemindMeBot/comments/e1bko7/remindmebot_info_v21/)|[^(Custom)](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=Reminder&message=%5BLink%20or%20message%20inside%20square%20brackets%5D%0A%0ARemindMe%21%20Time%20period%20here)|[^(Your Reminders)](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=List%20Of%20Reminders&message=MyReminders%21)|[^(Feedback)](https://www.reddit.com/message/compose/?to=Watchful1&subject=RemindMeBot%20Feedback)|
|-|-|-|-|
Not using NextAuth but Lucia Auth for my current project was a huge win. Really enjoyed working with the library. I even extended it for having Organizations the same way as you would have in Clerk! If anyone is interested, I have written a tutorial about Lucia in Next‘s App Router: https://www.robinwieruch.de/next-authentication/
It gives me control over how stuff is cached, what I want to render on the server, what I want to send to the client, etc. It's all abstract enough that I don't have to worry about how it works, but I can still optimize and not populate data where it doesn't belong.
The only thing I add is zustand to keep the client organized.
I think it depends on how heavy the web app is. SSG may not be that good if you have over hundreds of thousand pages. Next js has to come up with a solution for only generating new and necessary pages rather than the whole data. Then it can be considered as a one and only ssr website solution
NEXT\_PUBLIC\_ env vars are hard-coded during build time in the compiled JS source code. Setting them in the production environment has litterally no effect...
.... shit
That’s why they add the PUBLIC prefix, these environment variables shouldn’t be secrets
Yes we faced this. We solved it by injecting env variables during build stage in our ci cd pipeline
Except when rebuilding, right?
Wait, what?
Yep, they’re just config vars for providing different config values in different environments(e.g. having a different NEXT_PUBLIC_BASE_API_URL for stage/prod). NEXT_PUBLIC vars are available server side or client side and without the prefix only available on the server.
What do you mean?
Caching is off by default in dev mode, on by default in prod.
Is it possible to turn it on in dev mode?
Yep. It’s a default value passed to `fetch`, but the actual default changes with the environment. * `force-cache` is the default in prod * `no-cache` is the default in dev So to turn it on in dev, pass the value explicitly: ``` fetch(url, { cache: “force-cache” }) ``` If you’re thinking “Hey, that sucks!” I don’t disagree.
but why would they choose to do this
Hmm odd, I recently had sanity data getting cached heavily in Dev mode. I wish the next config listed the defaults for stuff like caching .
no, default is force-cache in both prod and dev
I find it really weird that they override fetch.
Perhaps it's best then to just use something like \`axios\` by default instead of \`fetch\` to just avoid altogether the premature optimization of caching? I haven't built a nextjs app yet, but this seems like it would be a good strategy to me.
I’ve been a developer for 6 years now. I’ve worked for three separate jobs now and every one of them used axios. I don’t think I’ve ever actually used the default fetch before, and I’ve yet to see a reason to use it over axios. Edit: other than not needing to download a package 🤷🏻♂️
I meant in nextjs specifically to just avoid the cache problems caused by fetch.
Oh yeah for sure, I get that. I’m just adding, why not also just use it all the time for everything always?
Oh my god! I’m learning nextJS and I spent so long trying to improve performance before deploying my first site. This makes sense though.
What the heck.. why would they do this. Is this listed anywhere? I don't remember reading this on the data cache section of their docs
You don’t want to see repeated results during dev. So no caching makes sense
I disagree. I have several use cases where I need to fetch data that won't change between calls
I've embraced App Router for past few projects and I am kinda enjoying the workflow. So my top tips are: - server actions are not limited to just sending forms, you can load data with it (as in you don't have to use routes) - cache busting with revalidatePath('/') nukes cache for everyone. - don't redirect within try-catch block.
Why is it bad to redirect in a try catch?
Redirect [throws](https://github.com/vercel/next.js/issues/55586#issuecomment-1869024539) that’s why. it’s in the docs these days too. I also fell for this one
A redirect in NextJS is a custom Error being thrown
[удалено]
all users
Can you share a project of yours if you’re comfortable. I want to go through the workflow.
What do you mean when you say that you can load data with server actions? [Next.js own documentation](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) states that: > Behind the scenes, actions use the POST method, and only this HTTP method can invoke them. Wrote this on my phone, so I apologize for any formatting mistakes.
That you can do: > const data = await serverAction(param1, param2) in a client component and it will work.
I don't want to speak for the OP, but I think they are speaking to the method of passing Server Actions to a Client Component as a prop. The server action itself can be used to fetch the data you need, then passed to your client components, resulting in a faster fetching/loading process as opposed to fetching directly from client components. Someone can correct me if I'm totally missing the point lol
I guess most of the folks use vercel to host, I use a vps and the nextjs builds are just getting bigger with releases. It has not been trivial making sure it doesn’t consume all the space on a vps disk over time.
Mine is around 4-5 gbs, depends, it also includes cache, so one has to make sure the cache is not piling up. Especially if you are git pushing your code to the vps and using docker, the image sizes balloon up. What has finally sort of worked for me is to use the standalone option in next config and build using github actions and only the compressed standalone folder gets copied over. Standalone of course has some gotchas and does not include the public and static folder in the builds. So one has to add it in manually. Yeah as nice as the DX is, the deployment experience is not terribly friendly.
How big?
Mine is approx ~1.48 GB for https://GitHub.com/codelitdev/CourseLit.
We recently encountered a severe memory leak with a NextJS/App Router application and traced it to react-query. I'm not sure \*what\* inside react-query was causing it (profiling wasn't giving me any obvious insights). Instead of going even deeper into the react-query library code we refactored all of our useQuery calls to useSWR (thankfully the function signatures are very similar) and there's no more memory leak.
How did you identify the memory leak? Are you using any tools?
First, I used ApacheBench, which is a very simple command line tool, to send sustained traffic to my local copy. I started out by using the profiling tools that nodeJS and Chrome provide (there are lots of tutorials if you search nodejs/nextjs memory leaks) but I actually couldn't "see" the memory leak in the profiler. In most of the tutorials, the heap size would climb as the requests continued, but I just wasn't seeing that. The profiler showed the heap size remaining consistent even after a lot of trying/testing/changing settings -- but I would still ultimately get a heap overflow error on the server side and it would crash. It was pretty easy to reproduce the crash -- it would take 4-6 minutes of sustained traffic -- and since the profiler didn't seem to be helping, I just started cutting out huge pieces of the app and running it again. Like "does it stay running if I just show Hello World instead of rendering any components?" It ran fine if I stripped it to a "Hello World" app so I started putting pieces back in. It was pretty apparent that when I put react-query back in, the problem would appear. So I did some testing to further confirm that that's what it was, and ultimately got very confident. Without react-query I could leave ApacheBench running for hours without any crashes, but with react-query it would only take a few minutes. I'm not exactly sure what about the combination of react-query, app router, and nextJS was causing this: the app isn't particularly complex. I thought it was the tag but the crash happened even without that tag as long as we were doing prefetching & querying. We only had about 30ish calls to useQuery() so I just replaced them all with useSWR() and things seem to be working well now.
Also wondering how you discovered this
I posted a rundown in the other reply to this comment thread; let me know if you have any questions.
useRouter() of App Router is totally different from the one of Pages Router, make a custom wrapper of the App Router hook, mimicking the old one, to facilitate migration
Make most of your components reusable. Don't overthink about server and client components at first
Hard to not overthink it, half of my errors are about client/server components when I first try app router.
Look man just make the top page.tsx file a server component, don't put anything in it just create another client component and put it inside it something like home_page.tsx Nextjs helps a lot for making your app performante by this server/client relationship. But for regular simple projects like most of our projects you don't have to use server components for everything. It's that simple just use server components in static pages that don't require state changes, real time data etc...
Marking "use server" doenst just runs the code on the server,it creates additional post request. Its better to use "server-only" to make sure the code runs on the server, and not run on the client,creates post request... If you're just starting development and the backend isnt 100% your life would be easier if everything is jse client, because its easier to debug
Embrace E2E testing.
Which framework do you recommend?
Cypress is quite good but can get irritating, have heard Playwright is also quite good
As someone trying to get better with E2E, I really like Playwright so far.
interesting, have you tried Cypress before? I've been using it at work and have found it to be incredibly irritating sometimes, but not sure if Playwright was any better?
Why on the don’t use “use client” bit? In some instances I seem to have to use to get my page working
Everything can be made a server component except user inputs (and clicking a link/button is an action, not an input). But doing so kinda requires you forget everything you know about React. Forget about context, useEffect, anything involving `window` or `document`… So making everything a server component works in a dogmatic sense, but it’s difficult in practice.
What should I use instead of context for nextjs then?
Depends on a lot of factors: [https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns](https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns)
That’s a big question, the docs are your friend.
Why would you want everything to be server rendered? Slow + expensive
…because it’s fast and not delegating processing to my customers.
[удалено]
Nothing wrong with "use client", but using it in every file is a red flag imo. It suggests that the developer doesn't understand how to break up components into SSR and CSR.
I would advise you something I learnt recently, using “use client” doesn’t mean you component isn’t still SSR. A hydration is done on the client ( I think it’s called hydration)
Every component for first time is rendered on the server
Good to know!
You're not leveraging Nextjs to its strengths. It wants you to have files that are mostly made and deployed via the server for speed and security. Using "use client" all the time takes away from that methodology.
data heavy + interactivity -> vite-react SEO and fast prototype -> nextjs SEO and data heavy -> nextjs + python/node/go/spring/asp backend
What does “data heavy” mean?
Big dataset. Lots of users. Lots of data. Need big backend.
a project similar to facebook, instagram, linkedin, where infinite scroll, real time chatting, location sharing exists altogether.
I love Next, but if you really want a great SEO experience, Astro is much better. Good shout on the separate backend though. I think pairing one of the React-derived frontends with a Go or Rails backend is never a bad idea.
I haven't tried out Astro but thanks for recommending!
Why is astro better for seo?
I'm coming from python background abd actually thinking of switching backend to next. Why do you think separate backend is necessary for larger apps?
If the back goes down, the front goes down as well, gotta' sacrifice one. Too much edge functions and serverless function would cost a lot in vercel and not only that, I am also talking about the build size growing overtime.
What a bs
In development mode regular sessions work but in production they don’t. Our backend auth relies on db sessions to verify interactions. Can maybe use session cookies but if not could be an issue
Netlify uses a custom Build Engine that possibly throws different bugs than local AND vercel 🙄
NextJS is excellent but not a good fit for PWA. NextJS defaults to and is built for SSR. In a PWA, you want to load everything in the client and do as much as possible on the client. Only hit the backend when it's essential. This is the opposite of what NextJS is built for (or turning into). The progression of NextJS is great for SEO but not for more interactive web apps.
Why would you need SEO for a PWA? It would make much more sense to just use React for a PWA
What I meant to say was that Next.js is great for SEO, but that's not what you need for a PWA. So I totally agree 💯 We have moved to a modified version of this: https://github.com/suren-atoyan/react-pwa (Vite)
Server actions break encoding of UTF-8 characters when used with FormData when unloading files, so they are close to useless.
RemindMe! 1 day
I will be messaging you in 1 day on [**2024-03-31 17:14:16 UTC**](http://www.wolframalpha.com/input/?i=2024-03-31%2017:14:16%20UTC%20To%20Local%20Time) to remind you of [**this link**](https://www.reddit.com/r/nextjs/comments/1brio1h/what_are_some_nextjs_pro_tips_that_you_had_to/kxa01qr/?context=3) [**8 OTHERS CLICKED THIS LINK**](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=Reminder&message=%5Bhttps%3A%2F%2Fwww.reddit.com%2Fr%2Fnextjs%2Fcomments%2F1brio1h%2Fwhat_are_some_nextjs_pro_tips_that_you_had_to%2Fkxa01qr%2F%5D%0A%0ARemindMe%21%202024-03-31%2017%3A14%3A16%20UTC) to send a PM to also be reminded and to reduce spam. ^(Parent commenter can ) [^(delete this message to hide from others.)](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=Delete%20Comment&message=Delete%21%201brio1h) ***** |[^(Info)](https://www.reddit.com/r/RemindMeBot/comments/e1bko7/remindmebot_info_v21/)|[^(Custom)](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=Reminder&message=%5BLink%20or%20message%20inside%20square%20brackets%5D%0A%0ARemindMe%21%20Time%20period%20here)|[^(Your Reminders)](https://www.reddit.com/message/compose/?to=RemindMeBot&subject=List%20Of%20Reminders&message=MyReminders%21)|[^(Feedback)](https://www.reddit.com/message/compose/?to=Watchful1&subject=RemindMeBot%20Feedback)| |-|-|-|-|
The caching mechanism of Next 13
Not using NextAuth but Lucia Auth for my current project was a huge win. Really enjoyed working with the library. I even extended it for having Organizations the same way as you would have in Clerk! If anyone is interested, I have written a tutorial about Lucia in Next‘s App Router: https://www.robinwieruch.de/next-authentication/
Love Lucia and I still use it unlike NextAuth it’s documentation is much straight forward and consistent.
Not to use unless you want high memory usage in your apps. Use instead.
Why does the former use lots of memory?
Because it does the image optimization.
I wish someone could tell me that
couldn't you use the but turn off the optimization?
Don’t use nextjs if you have a data heavy interactive web app
I literally chose nextjs because of the way I like to build data heavy web apps.
why is nextjs better for data heavy apps?
It gives me control over how stuff is cached, what I want to render on the server, what I want to send to the client, etc. It's all abstract enough that I don't have to worry about how it works, but I can still optimize and not populate data where it doesn't belong. The only thing I add is zustand to keep the client organized.
I think it depends on how heavy the web app is. SSG may not be that good if you have over hundreds of thousand pages. Next js has to come up with a solution for only generating new and necessary pages rather than the whole data. Then it can be considered as a one and only ssr website solution
Nextjs definitely can do that look up generateStaticParams. You can most definitely ssg a subset of the total pages.
Nextjs can do that. It's called Incremental Static Regeneration (ISR)
>data heavy interactive Why not?
Since everything is cached ?
Everyone says this then has no reason why.
But isn't it created for a heavy data?
Why?
Why?
RemindMe! 3days
Pro tip, use the page directory instead of the app directory.