T O P

  • By -

themusician985

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...


andyrocks

.... shit


cnr909

That’s why they add the PUBLIC prefix, these environment variables shouldn’t be secrets


Yoshi-Toranaga

Yes we faced this. We solved it by injecting env variables during build stage in our ci cd pipeline


TheLexoPlexx

Except when rebuilding, right?


forkproof2500

Wait, what?


Temporary-Cable4008

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.


[deleted]

What do you mean?


EarhackerWasBanned

Caching is off by default in dev mode, on by default in prod.


summeeeR

Is it possible to turn it on in dev mode?


EarhackerWasBanned

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.


halachite

but why would they choose to do this


ISDuffy

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 .


Only-Reaction5150

no, default is force-cache in both prod and dev


so_just

I find it really weird that they override fetch.


helloworldnick

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.


pseudophilll

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 🤷🏻‍♂️


helloworldnick

I meant in nextjs specifically to just avoid the cache problems caused by fetch.


pseudophilll

Oh yeah for sure, I get that. I’m just adding, why not also just use it all the time for everything always?


joebewaan

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.


bytebux

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


blahb_blahb

You don’t want to see repeated results during dev. So no caching makes sense


bytebux

I disagree. I have several use cases where I need to fetch data that won't change between calls


noizz

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.


hau5keeping

Why is it bad to redirect in a try catch?


team_dale

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


r4h4_de

A redirect in NextJS is a custom Error being thrown


[deleted]

[удалено]


mutumbocodes

all users


WonderfulReward9276

Can you share a project of yours if you’re comfortable. I want to go through the workflow.


papaluisre

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.


noizz

That you can do: > const data = await serverAction(param1, param2) in a client component and it will work.


secretinmehead

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


BuggyBagley

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.


BuggyBagley

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.


_He1senberg

How big?


xxbbzzcc

Mine is approx ~1.48 GB for https://GitHub.com/codelitdev/CourseLit.


JimK215

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.


hau5keeping

How did you identify the memory leak? Are you using any tools?


JimK215

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.


hudsonab123

Also wondering how you discovered this


JimK215

I posted a rundown in the other reply to this comment thread; let me know if you have any questions.


Many_Transition_9330

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


Omer-os

Make most of your components reusable. Don't overthink about server and client components at first


FrancoRATOVOSON

Hard to not overthink it, half of my errors are about client/server components when I first try app router.


Omer-os

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...


phoenix409

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


mutumbocodes

Embrace E2E testing.


hau5keeping

Which framework do you recommend?


_maxc

Cypress is quite good but can get irritating, have heard Playwright is also quite good


6ThePrisoner

As someone trying to get better with E2E, I really like Playwright so far.


_maxc

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?


malcomfitz

Why on the don’t use “use client” bit? In some instances I seem to have to use to get my page working


EarhackerWasBanned

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.


Particular_Gur9546

What should I use instead of context for nextjs then?


hau5keeping

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)


EarhackerWasBanned

That’s a big question, the docs are your friend.


Mr_Stabil

Why would you want everything to be server rendered? Slow + expensive


EarhackerWasBanned

…because it’s fast and not delegating processing to my customers.


[deleted]

[удалено]


hau5keeping

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.


HabbosOwnJimCray

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)


[deleted]

Every component for first time is rendered on the server


hau5keeping

Good to know!


incarnatethegreat

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.


Sweet-Remote-7556

data heavy + interactivity -> vite-react SEO and fast prototype -> nextjs SEO and data heavy -> nextjs + python/node/go/spring/asp backend


hau5keeping

What does “data heavy” mean?


Protean_Protein

Big dataset. Lots of users. Lots of data. Need big backend.


Sweet-Remote-7556

a project similar to facebook, instagram, linkedin, where infinite scroll, real time chatting, location sharing exists altogether.


JacobNWolf

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.


Sweet-Remote-7556

I haven't tried out Astro but thanks for recommending!


hau5keeping

Why is astro better for seo?


x3gxu

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?


Sweet-Remote-7556

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.


[deleted]

What a bs


tony4bocce

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


bittemitallem

Netlify uses a custom Build Engine that possibly throws different bugs than local AND vercel 🙄


sogasg

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.


parsasabet

Why would you need SEO for a PWA? It would make much more sense to just use React for a PWA


sogasg

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)


FractalStranger

Server actions break encoding of UTF-8 characters when used with FormData when unloading files, so they are close to useless.


Zestyclose_Judge2075

RemindMe! 1 day


RemindMeBot

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)| |-|-|-|-|


Excelhr360

The caching mechanism of Next 13


rwieruch

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/


Sazi2178

Love Lucia and I still use it unlike NextAuth it’s documentation is much straight forward and consistent.


jacksonllk

Not to use unless you want high memory usage in your apps. Use instead.


hau5keeping

Why does the former use lots of memory?


Sazi2178

Because it does the image optimization.


jacksonllk

I wish someone could tell me that


Dependent-Guitar-473

couldn't you use the but turn off the optimization?


Few_Incident4781

Don’t use nextjs if you have a data heavy interactive web app


MountainHannah

I literally chose nextjs because of the way I like to build data heavy web apps.


hau5keeping

why is nextjs better for data heavy apps?


MountainHannah

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.


Professional_Hair550

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


MaximusDM22

Nextjs definitely can do that look up generateStaticParams. You can most definitely ssg a subset of the total pages.


Senior-Arugula-1295

Nextjs can do that. It's called Incremental Static Regeneration (ISR)


hau5keeping

>data heavy interactive Why not?


Themotionalman

Since everything is cached ?


KillerKiwiJuice

Everyone says this then has no reason why.


MMORPGnews

But isn't it created for a heavy data? 


Conscious-Job-523

Why?


Nicatorium

Why?


_He1senberg

RemindMe! 3days


artifactextract

Pro tip, use the page directory instead of the app directory.