I don't think the issue is that you are biting off too much. The issue is that you try to do too many new things at once.
Ditch prisma, ditch typescript and just try something simple.There is not reason why you shouldn't use mysql if that's what you are familiar with.either build a standalone API that will be consumed by your next.js app or skip this step and just do it in next.js https://nextjs.org/docs/api-routes/introduction
for connecting to the database use something like knex and play around... once you are comfortable with this ecosystem then add typescript and then aftewards add prisma or whatever you want
Currently, not yet. Soon, yup.
The next big step in React seems to be Server Components where it's basically the component managing the data it needs on the server side (i.e. fetching) and delivers to the client only the code it needs (i.e. static DOM).
Next.js should naturally follow this path; maybe they'll address it during their conference happening on the 15th of June (https://nextjs.org/conf)
More info about React Server Components: https://reactjs.org/blog/2020/12/21/data-fetching-with-react-server-components.html
It indeed is for authentication, localization, bot detection etc.
It indeed is for authentication, localization, bot detection, etc.- https://vercel.com/features/edge-functions#examples
I'm not an expert by any means and can't answer all your questions but I'll say that I think if it is critical the data is as fresh as possible, SSG/ISR is inefficient and you should be using SSR. If the data is coming from a CMS and presumably not changing every second, your revalidate should be longer... and ideally you should use deploy hooks to integrate with your CMS and manually trigger a build when you change/add content.
So Next runs on both the server side and the client side.
Anything that uses fs
must be run on the server side because fs
is the Node file-system module. Importing it creates the error because whenever you import code, you also import everything which that code imports... unless it doesn't exist, then you get errors like this.
Try moving whatever logic you're using to an API route and then calling that API from your client.
I'd recommend reading through the Next.js docs to better understand how you can use the framework. You can fetch data with client-side rendering and use Next.js as a single page app, just like Create React App. Then the question isn't "which framework is better?" but more so "which data fetching strategy makes the most sense for my use case?"
Next.js is an opinionated framework for building React applications.
React, alone, is just a library. To make an typical react application, you need much more than React. You need Babel to transpile your JSX. You need webpack to bundle your code into packages a web browser can consume. You need plugins and a bunch of configuration to make things like CSS/SCSS work. If you are building a Single Page Application (SPA), you need some library to handle routing (e.g. react-router). If you want to marry data from a data source (e.g. a database) to create a site using static site generation (SSG), you need an engine that renders static pages from your React templates based on the data. And so on...
Next.js solves addresses all those things (and more) in an easy to use package. Of course there are other frameworks that also address those things (e.g. Create React App). One of the main differences with Next.js is that is also provides a backend runtime that supports server side rendering (SSR) which is much better for SEO as the initial response from the browser is a fully rendered page instead of a skeleton that gets filled out a half second later with content when React spins up.
Next.js also provides more interesting approaches than simple SSR like incremental static regeneration (ISR) which combine some of the best parts of SSR and SSG.
Finally, Next.js also provides a basic set of capabilities for exposing APIs from the backend (which might otherwise have been created separately with an Express.js backend).
The front page of https://nextjs.org/ has a pretty good section on "Why?". You can do all the things that Next.js enables without Next.js, but it will be a lot of work. Next.js lets you focus on your application instead of on plumbing.
Just a quick note: using a free Heroku database is fine for practice and a hobby app that doesn't get real traffic, but Heroku's free databases aren't intended for this use-case, and this setup will eventually break. There are two reasons:
If you want to use Prisma and a cloud Postgres offering with Next's /api pages, I'd recommend Supabase's cloud Postgres database, which is well-suited to this kind of use case and offers a free tier. The team developing it is super responsive, too (in fact, I bet a developer for their team will chip in soon :))
Are you prepending your variables with NEXT_PUBLIC_ ? You’ll need to if you want to use them on the client.
If you're using ISR (https://vercel.com/docs/concepts/next.js/incremental-static-regeneration), you can have the page update at fixed intervals.
Assuming the typo is content and being pulled in from a CMS or something, as opposed to being part of the code itself. If you're changing code, you're redeploying.
They have a whole section about converting create-react-app to next, which is pretty awesome. This is probably helpful even for a general react app.
getStaticProps
is only executed at build time, so whatever data is present when you do your deployment is what's going to be shown on the site.
You have two options to fetch new data with getStaticProps
:
Or at least the real-time notifications part of your backend. Firebase Realtime Database, Pusher, Ably, etc, can all be providers for just the realtime parts of your application.
https://vercel.com/docs/solutions/realtime
Though you can also just put your entire backend elsewhere too if that makes more sense for your use case.
This, in combination with the native internationalized routing capabilities of Next.js: https://nextjs.org/docs/advanced-features/i18n-routing
Having both of these should get you pretty far. Also, don't worry about none of the languages being English. Most translation related libraries don't assume anything about a "base" language so you should be fine.
It's very important to also read up on the "loaders" section of the next/image documentation (https://nextjs.org/docs/basic-features/image-optimization#loader). If you setup a loader, Next.js doesn't actually do the image processing itself, it just creates a URL with image dimensions and quality for your image service to handle.
In your case you assume that all customers benefit from seeing the post cover as a 500x500 image, and not scaled up or scaled down. But different devices need different images. Some might benefit from a 1000x1000 resolution image, some 250x250. Some might want webp as a format, some can't handle that and want jpg instead.
Next/image makes all these decisions for you and adds some cool stuff like lazy loading and "blur up" image loading. Things you'd all have to do yourself or with an external library if you don't use next/image.
So, I would first reevaluate whether your architecture for a custom image back end in S3 is actually the best option. Why not use an image CDN built for this, like Cloudinary, Imgix, etc. Or create your own custom next/image loader and use any image CDN with enough features to your liking?
Second: check if you're not making too many assumptions about the devices people will use to check your application. If you let go off these assumptions you might find that next/image is a very helpful tool to serve images exactly the way your visitors need it.
Good luck with your project! 👍
It looks like environment variables are what you’re looking for: https://nextjs.org/docs/basic-features/environment-variables
These allow you to set a constant in a config file then use them in your code. On production you set a different value for this variable. Vercel, for example, let’s you set these variables for each environment.
There are two kinds of Next.js env variables too - ones the client can see which are good when you need an API endpoint for the client to switch (which start with NEXT_) and server side only Env variables which are good for things the client should never see.
Using this approach you could set a API_ENDPOINT variable and use that with process.env.API_ENDPOINT in your server side props function. If you need to use this variable on the client side, you’ll switch it to NEXT_API_ENDPOINT and access it from both.
I typically have the pages
folder (as is required) and a sibling folder called src
. This folder is usually broken down into client
and server
folders, and from there I would have stuff like you mentioned, components
, styles
, utils
, etc, in the client
folder.
You can cut down on path lengths by aliasing paths. I usually at least create a mapping to my src
folder, but you can get crazier.
I'd guess that you're deploying to a serverless environment like Vercel. The problem with file uploads there is that the filesystem is ephemeral; that is, the files stored on it will only exist on that one system, and only until it spins back down shortly after use.
Instead, you'll need to use a different service for storing those files. Vercel has a whole docs page with recommendations.
I would recommend taking a look at StoryBlok (https://www.storyblok.com/) - their component/live visual editor works really nicely for page building and gives a whole bunch of flexibility that is way harder to achieve with Prismic/Contentful, plugins are also really easy to make and integrate compared to how I found Contentful’s app ecosystem - for more clear structured content though I think Contentful/Prismic probably have an edge.
Of course not! I choose the color on my own and the illustrations are coming from Figma Community! It is total free to use!! https://www.figma.com/community/explore this is an amazing community that I just notice that not a lot of people heard of it. 😅😅
Not an expert, but you are doing great. What you need to do is style the output.
Something like TailwindCSS makes that a breeze.
https://nextjs.org/blog/markdown
Or you can check this out
https://www.pullrequest.com/blog/build-a-blog-with-nextjs-and-markdown/
Best of luck.
You have to be explicit in what paths are to be rendered with getStaticPaths
, even for a dynamic route. If you don't have a finite number of options for the slug, then you won't be able to prerender. Docs: https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation
To give a practical use-case for this, I built a site for a photographer recently. Several folders of images, varying numbers of images in each folder. I can use getStaticPaths
to read each folder and create a path for each image. Each of these image pages is now prerendered and can be accessed via that slug now at the [slug]
page.
I’d use a catch all route.
Let’s say you have a product page, pages/product.js.
This would get you mysite/product/some-product
To use a catch all route, rename product.js to […params].js and put the renamed file into a /product folder, like this: pages/product/[…params].js.
Now, you can add any amount of additional parameters to the URL and they’ll all be put into an array you can use on the product page.
For your request you would then use these URLs: - mysite/product/some-product - mysite/product/some-product/with-warranty - mysite/product/some-product/some-other-thing
Within product/[…params].js, you’ll now get an array like this from the router: - { “params”: [“some-product”] } - { “params”: [“some-product”, “with-warranty”] } - { “params”: [“some-product”, “some-other-thing”] }
For full documentation check out this page:
https://nextjs.org/docs/routing/dynamic-routes#catch-all-routes
Nice! Now it‘s time to add a smooth page transition ( set opacity ).
You can use framer-motion for this. It‘s fast and beautiful.
shared layouts also giving you a good user experience!
https://blog.sethcorker.com/shared-layout-page-transitions-nextjs-framer-motion
Yes. As simply as installing the app (and prereqs like Node.js) on any linux VM and running:
next buildnext start
This can quite easily be in a docker container as well. There are many many places you could choose to host this way. Many places (I have tried both Azure and DigitalOcean) have app platforms that you can just point at your repo and they will detect that it's a node.js app and build the docker image for you every time you commit.
If you want serverless, the choices are reduced but there are still several. AWS Amplify does it, Netlify does it. I expect there are others, but those are the two I see most often. You can also roll your own if you want, it's just more work than the next start
option above.
See for more details on both the Node.js and Docker options in the official docs here: https://nextjs.org/docs/deployment#other-hosting-options
The Angular CLI is absolutely fantastic!
I would love to go like
nx create page dashboard
(Where dashboard would be the name)
And it would create the whole thing within the right directories etc
Have you heard about incremental static generation? It's a feature for Next.js apps on Vercel, and it's one possible solution to your problem.
Vercel doesn't recommend you use CloudFlare's proxy (see link below for details), but you certainly can use their DNS service. I do.
Vercel already has a CDN for all your static content, so the Cloudflare CDN is sort of redundant.
https://vercel.com/support/articles/using-cloudflare-with-vercel
Is there a reason you can't use the NextJS dynamic ?
​
https://nextjs.org/docs/advanced-features/dynamic-import
​
Might have better luck.
NextJS is a framework that includes a react based front end and a node based backend, so no real need to have a separate node backend.
You might be looking for this:
https://nextjs.org/docs/advanced-features/custom-server
Where you can override or extend the built-in backend of NextJS
Also, if you are completely new to NextJS you might find this walkthrough helpful. It's not too long and walks you through the main parts of a Next app:
It may seem wrong, but what you are experiencing is simply how Next-js currently functions. They mention it under 'caveats' at the bottom of this page: https://nextjs.org/docs/advanced-features/automatic-static-optimization
Simply stated: if u add getInitialProps to _app, and actually need live data on each page, forget about static page generation. It would be nice if they added this functionality in the future, but it would somehow devaluate the use of static generation if some data on the page should still be fetched and the DOM rerendered.
For now: u could just use getInitialProps on the about.js page, disabling static generation all together. (Im still waiting for a way to use getServerSideprops on app.js)
It is, next has naturally a server that is used when calling getInitialProps in server side rendering or with the api routes, that I think it is the case you are looking for. Check https://nextjs.org/docs/api-routes/introduction
Do you have React experience? If so, I recommend just going with Vercel's own starter tutorial https://nextjs.org/learn/basics/create-nextjs-app
If you are new to frontend and/or React, I recommend starting there before tackling Next.
Like the other comment says, you do them as two separate projects. I personally prefer putting another app in a subpath instead of a subdomain though:
Obligatory not-sure-if-this-is-an-anti-pattern or if there's other issues that may come into play here, but just re-exporting the home page like this example and tying in the same alias as in your example also works if you really don't like query params. Does seem to be less performant in general though since you're duplicating pages and causing full routing events when opening / closing modal, could be an issue.
You could use a NextJS rewrite: https://nextjs.org/docs/api-reference/next.config.js/rewrites
You could add something like:
async rewrites() {
return [
{
source: '/products/lenovo12T:opt*',
destination: '/product',
},
];
},
This would render the /product page for /products/lenovo12T and anything else after the 12T (like -with-warranty or whatever).
You can then read the opt param in the page component to see if it says "-with-warranty" or whatever you want.
An EC2 ubuntu server is just a linux box.
Ultimately, it boils down to:
In practice, assuming you want something more production like, you'll probably want more pieces like pm2 to keep the server running. You'll want some kind of proxy server to handle TLS, etc. That could be nginx on the ec2 box or AWS Application Load Balancer, etc.
Ultimately, the good news is that when you run next.js on your own server (which is what EC2 is) you can choose the technology you want to use. The bad news is that you have to choose the technology you want to use.
If you're not sure what you want, I'd just follow one of the many "running next.js on your own server" guides that are out there. For example: https://dev.to/reactstockholm/setup-a-next-js-project-with-pm2-nginx-and-yarn-on-ubuntu-18-04-22c9
Personally, I'd probably not use EC2 to host a next.js app as it's too much manual work for my tastes. To use AWS as a cloud provider, I'd probably use AWS amplify to so that I didn't have to take care of the details above. If I wanted a little more hands on control, I'd probably build my app into a docker container and then deploy it with AWS Elastic Container Services (ECS) so that I don't have to manage the underlying VM details.
I mean you can also just trigger a build on a webhook from your CMS: https://vercel.com/docs/concepts/git/deploy-hooks.
Also, if you set the revalidate to 1 minute or something, is that really so bad? You'd get a hit to your database once a minute maximum. That's not exactly straining the server.
Not sure why you'd use GitHub Actions with Vercel, but it's pretty easy if you're just using Vercel: https://vercel.com/support/articles/set-up-a-staging-environment-on-vercel
You can, actually. You get a bunch of specific optimizations if you deploy Next to Vercel without a custom server, but Vercel provides several different runtimes you can use to deploy all sorts of apps: https://vercel.com/docs/runtimes
It doesn't really for truely real-time scenarios. Vercel developed it and so they push it a lot.
It's a good library, but it's really just a tool for making an old-school HTTP request to a REST backend. As for semi-real-time, you can configure it to refresh the data on an interval (every few seconds) and it handles only re-rendering your react components when data actually changes.
If your real time needs are only semi-realtime (i.e. you have a dashboard and you want to show changes as they happen over the course of a day), then you may be fine with something that is only as real-time as "every few seconds". Using SWR or react-query (a similar open source library) are a heck of a lot easier than something that with real websockets.
But if you are making a chat app or want to create a collaborative document editing app where you want users to see each other typing and moving their cursors around in real time, you'll need something more instantaneous that than and will want to look at one of the other options.
Vercel has a guild on using Pusher here (I have no idea of Pusher, specifically, is good as I have never used it): https://vercel.com/guides/deploying-pusher-channels-with-vercel
The default has changed to us-east now: https://vercel.com/changelog/serverless-functions-are-now-deployed-to-us-east-by-default
I agree -- the /api pages are really nice if your back-end layer is fairly limited in scope because you get to live the dream of a single full-stack project.
If you compare Next's API routes to something like NestJS (the back-end framework that sounds the same but is totally different) it offers quite a bit of flexibility at the expense of additional code and a separate back-end to deploy and maintain.
Some of the advantages are:
Disadvantages:
So, I think if I were building a scope-limited project that doesn't have really cumbersome server-side requirements, I'd go with the NextJS API routes, but if I were building a large (or potentially large) project where the structure and consistency of something like NestJS (or a well-designed Express app) starts to be more helpful, I'd elect to build a standalone back-end app instead.
You can do that by using catch-all-routes and splitting your string into an array. Example code:
export default function DayPage({ food }) { return <div>{food}</div>; }
export function getStaticPaths() { return { paths: [{ params: { food: ["food 12", "3 4"] } }], fallback: true }; }
export function getStaticProps(ctx) { return { props: { food: ctx.params.food } }; }
Hey folks, Vercel's CEO here. We actively deal with problematic ISPs throughout the world on a regular basis. Our priority is to preserve access to everyone, everywhere, commensurate with local laws and regulations.
In some cases, ISPs are actively inhibiting a large part of the internet by taking an outdated and flawed approach to trying to protect their users. With the rise of privacy-preserving services like Apple's Private Relay, the idea of a single IP representing millions of users will only become more common.
We're taking action to get the IPs off that list right away. Whoever put the IP on that list, and the ISP that downloaded it, is punishing both "nextjs.org" which you use every day, and some other deploy in the same motion. We have a team on call 24x7 when abuse gets reported and it's handled appropriately, so this IP block ends up being completely unnecessary.
(Our Enterprise tier offers dedicated IP pools, but millions of subdomains and domains of our platforms can't each get their own. We must keep all of them online.)
I wouldn’t use redux for that use. You can do auth checks using next-auth and load the server side props to have them ready but only show them if the user is logged in. Or you can even use context to pass the global logged in variable.
Here is a few examples:
https://nextjs.org/docs/authentication
https://link.medium.com/LzpDNyFY1ib (this one uses context for state)
As a practice I use hooks -> context -> useReducer (which is still a hook) -> lastly Redux.. in that order..
I feel like too much state adds more complexity than necessary, plus added weight to your project which can hamper any performance gains you are looking to achieve.
Nextjs doc is both well-written and really easy to use. https://nextjs.org/docs/basic-features/data-fetching I highly suggest you rely on it, unlike most doc, you'll often only need this one to build your app.
Their example of getstaticprops uses data fetching to initialize components. However, it happens at build time.
I'm not using redux (as someone wiser than me said : "don't use redux until you really need it", and I've never needed it despite having a moderate size project), but the most likely answer is you should pass initial, raw data using getstaticprops, and then do redux stuff in useEffect hooks accessing the data returned by getstaticprops using props.
getstaticprops is happening at build time, so it doesn't have access to the component state of the page displayed in the user's browser. Again, I don't know redux.
It's tough being more specific without more info on what you're trying to achieve.
One final word of advice : tackling for nextjs and redux at the same time is probably a tough cookie. Try to get a grasp on nextjs and react first, then decide if you need redux or not. The answer is probably you don't need it.
Yes. Running the start script will start up a node server.
If you really wanted to you can even customize this node server, see https://nextjs.org/docs/advanced-features/custom-server. In which case end up with a server.js file and just run it like you would a server script with express. Next just hides that bit from you.
Hey u/Stackerito! I'm Delba from Vercel.
If you want to extend the Babel config, for example, by using "next/core-web-vitals"
, you have to set "next/babel"
as your .babelrc
file will be considered the source of truth and you'll need to explicitly define the next preset. There's more information on the Next.js docs here. You've configured it correctly and using an array for the "preset" option is a commonly used Babel convention.
For question 2, were you getting the error with or without "extends": "next/core-web-vitals"
option?
What is your aim with adding the suffix?
If its just visual in the url bar, then you could make use of rewrites, either in nextjs or in your server (nginx, apache, etc)
https://nextjs.org/docs/api-reference/next.config.js/rewrites
I’d say use next image even still. Yes the file size and resolution optimization is moot but next image does a lot more than that, including lazy loading, blur/placeholder values, preloading high priority images, and more. It’s painless to use so why not? check the docs for more info
make a new directory called store
and add a pants.js
page in it. But you will probably want to do some like store/[category].js
though. Check out the docs on dynamic routes
React apps can be deployed to pretty much anything, an S3 bucket for example. There's no "backend", you're just serving static files.
You can export static HTML from Next, but it does limit some of the features you can use.
If you're using a "standard" deploy of Next, you'll need to run it on a host that has node.js.
Not a big downside, but you should be aware of it.
Page specific: The serverless target will output a single lambda per page. This file is completely standalone and does not require any dependencies to run:
pages/index.js => .next/serverless/pages/index.js
pages/about.js => .next/serverless/pages/about.js
You can read about the issues here. At the end it mentions that using using PgBouncer prevents your application from exhausting the database's connection limit. If you use Supabase for your Postgres database, it comes with PgBouncer for free.
I'm sure you already ran into this, but just in case - that sounds like a good case for catchall routes (files marked as [...route].js, example here). Get each routing element individually through parameters, and just update the page state where you want it when the route params change, while sticking on effectively the same page / component so everything is snappy.
Also this thread totally didn't send me down a rabbit hole of implementing this for a separate personal project, lol
useContext
is part of React, not NextJS. To answer your question you can use Redux Toolkit in NextJS. Depending on the complexity of your state management you will in most cases be fine with just using https://reactjs.org/docs/context.html
This is a react error, not specifically to Next.js. https://reactjs.org/docs/lists-and-keys.html
Inside the contributions
loop, looped items should have a key
prop with a unique value within their siblings so react knows which looped item to update. If the order of items never changes, you can get away with using just the array index.
my quick JAM stack of choice currently is Next, Firebase, and Tailwind, so for me i’d:
Have the form submit to a firebase firestore collection, and then have a snapshot listenener on the viewing area/page that automatically updates as new form submits come in. could fade in or something
https://firebase.google.com/docs/firestore/query-data/listen
this is a client side approach to displaying the data.
you could also skip the snapshot listener and just load x results from the collection via SSR on each page refresh
Internally, hooks, context are implemented using JavaScript closures. But they serve different purpose. And together they are supposed to eliminate the need for an state management library like react-redux. As mentioned in the docs: "Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
In many cases it’s not possible to break these components into smaller ones because the stateful logic is all over the place. It’s also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library. However, that often introduces too much abstraction, requires you to jump between different files, and makes reusing components more difficult.
To solve this, Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods. You may also opt into managing the component’s local state with a reducer to make it more predictable."
So if you are ready to try hooks and context apis, you can get away completely from the complex implementation provided by state management libraries.
Do you have an understanding of how Props and State work in React?
If not, start there - it'll help you solve exactly this kind of problem and is fundamental to building in React.
There's a good tutorial here that could help: https://reactjs.org/docs/thinking-in-react.html
also if you tried next.config CORS variant did you change this
{ key: "Access-Control-Allow-Origin", value: "*" },
to
{ key: "Access-Control-Allow-Origin", value: "https:\\yoursite.com" },
Or again the env variable could be used here instead of hardcoding
Here’s my index.js ```
import React from 'react'; import Head from 'next/head' import Image from 'next/image' import styles from '../styles/Home.module.css' import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; //import AppBar from '@mui/material/AppBar' //import Toolbar from '@mui/material/Toolbar' import Typography from '@mui/material/Typography' //import Button from '@mui/material/Button' //import Link from 'next/link' import { Container } from '@mui/material' import FirebaseClient from '../FIREBASE/FirebaseClient' FirebaseClient()
export default function Home() { return ( <div className={styles.container}> <Head> <title>Create Next App</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head>
<Container> <h1>HOME PAGE</h1> </Container>
<footer className={styles.footer}> <a href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > Powered by{' '} <span className={styles.logo}> <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} /> </span> </a> </footer> </div> ) }
Nextjs offers routing out of the box, so you don't need to add an extra dependency. Others have already linked to the official documentation, and I'd say its a great way to start learning about it!
Edit: to add to the other resources linked here - https://nextjs.org/docs/routing/introduction
https://vercel.com/blog/nextjs-server-side-rendering-vs-static-generation
When using SSR it renders per request. When using static it renders the HTML at build time.
If really only one minor service needs to be called, I wouldn't go through the hassle of setting up a whole service for it, but rather just use serverless functions or even Github Actions. Vercel has a good example here
We had issues with a end users trying to access from China. This guide fixed it: https://vercel.com/support/articles/how-do-i-prevent-my-vercel-deployment-from-being-blocked-in-china?query=china%2520block
Yup - this is tricky. It's hard to cache pages with presigned URLs that expire.
Here's a few approaches I've used in the past with S3 and Next.js.
1) Use Vercel's ISR and set a revalidate
that is a bit shorter than your S3 expire timeout. This allows Vercel to regenerate the cached pages every so often and prevent them from holding stale S3 urls. This can be tricky on very low traffic websites, like 1 or 2 users visiting every few weeks, but works great otherwise. More info here: https://vercel.com/docs/next.js/incremental-static-regeneration#fetching-data
2) Don't generate the S3 urls in getStaticProps
. Instead only generate cacheable content and then at client-side runtime have React fetch the S3 urls from a Next.js API route that does all the signing. This ensures you always get fresh URL. Tradeoff here is that you won't have server rendered image tags, so rest of your content might load before your images.
3) If you can avoid it skip the presigned URLs. Instead generate an image url that includes a sha so it's impossible to guess. Depending on your security requirements this might be a non starter, but I've found this simple approach solves a lot of problems with SSG.
Hope this helps! Happy to go into more detail on any of these.
Consider an infrastructure where you have 3 nextjs server instances A, B & C, which are fronted by some kind of a load balancer that balances traffic to them. Let's say a user makes some request to your app and it gets routed to A. During the request to A, next/image will save the image (and resized images) to the local filesystem (instance-level cache). Then you can imagine that the next request to A will be served from the cache which will be much faster than downloading from S3, and converting it, and saving it, then sending it back to the user.
But notice, this will only happen if the next request gets to A. Chances are it won't because of B & C. And if you have a thousand instances, you can imagine why it'll be pretty much ineffective. So instead, I recommended the CDN cache because it caches everything returned from a URL pattern you define, with a cache policy you define. So every time a GET request is made to a particular URL for a specific image of a particular size, the request doesn't go to your nextjs server but can directly be fetched from the CDN which is much much faster.
You have to understand what Vercel is, and how it works. Their big selling point is their simplified platform for infrastructure where you don't have to think about it, but unless you're building a personal project, you have to be very careful about that. What they essentially do is abstract all the logic above away from you so you can "focus building your application" but if you expect to get some serious traffic on your site at some point, you have to and should worry about your infrastructure.
TLDR; Vercel has a CDN infront of their architecture (link) that basically does what I described above.
No, there is no downtime in deployments, regardless of the deployment stage. You can even switch projects to different accounts without downtime: https://vercel.com/blog/transfer-vercel-projects-with-zero-downtime
Your domain just routes to a different/new deployment after deploying.-
I don’t know if this is possible. You do, however, get an email when a deployment is successful via GitHub. Telegram is not integrated as of now, but slack is: https://vercel.com/integrations/slack. This might be what you are looking for. It says, “The Vercel integration for Slack gives your team the full picture on the deployments of Vercel projects in the Slack channel(s) of your choosing.”
They have their own Edge network. It’s documented here:
https://vercel.com/docs/edge-network/overview
In a nutshell:
Note, if the static content (the photos/illustrations) is user submitted and therefore not living in your source tree (e.g. your ./public/ folder) and is stead being served out of a database via an API route, it won’t look like static content to the Vercel engine and won’t be served from the CDN. In that case, you’re probably better off storing your “dynamic-static” images in a third party CDN and not serving them via NextJS/Vercel.
Actually no. You're developing with the next
command and the page will behave completely differently, e.g.: it will refetch data each time you reload it. Vercel runs next build
and then syncs the files to AWS where they will be executed as lambdas. To simulate this behaviour you can try <code>vercel dev</code> or next build && next start
.
Nope, you can still deploy with Heroku if you'd like! You need a Vercel account to view the dashboard, but you don't have to move your deployment.
It's somewhat complicated, but basically cookies are domain or origin specific. Browsers consider the port to be part of what defines an origin and so localhost:8080 and localhost:3000 are different web sites and won't see cookies from each other.
You're probably running into the new same-site cookie defaults in Chrome and Chromium browsers that prevent sites different from the page's origin from setting cookies by default.
See one explanation here: https://www.kevel.co/blog/chrome-samesite/
For what it's worth, I dropped styled-components a while ago for CSS modules (which works fine in Next 12 of course.)
Set a "theme" in a global stylesheet using root variables, like I did with this small project. And you're good to go.
If anyone says they need programmatic CSS I'd ask for receipts. I bet I can prove they've wasted their money.
To deploy a Next.js application under a sub-path of a domain you can use the basePath
config option.
basePath
allows you to set a path prefix for the application. For example, to use /app
instead of /
(the default), open next.config.js
and add the basePath
config:
module.exports = {
basePath: '/app',
}
Source: Base Path
CORS is a security feature of web browsers and is independent of Next.js and React.
CORS is specifically designed to prevent one web page from making HTTP requests in code (e.g. via fetch or XMLHttpRequest) to another web site unless that other web site gives permission. This permission is indicated by HTTP headers returned by the other web site that list what web pages are allowed to talk to it. You can't externally enable CORS for a web site that doesn't support it, itself (*except by proxying it, see below)
CORS doesn't apply when you make a request to the same web server that the page came from (i.e. when you talk to the Next.js API routes). It also doesn't apply when you use HTML Forms.
The reason you're seeing this with redirects is that when you redirect an API request, you're the browser, "hey, talk to this guy instead". And so the browser will try to make a request to that other URL and CORS will apply if it is a different server (different server means different hostname or different port).
The way to make this work is either to only call APIs from other servers that support CORS and are designed to be used this way, or proxy the API calls through the Next.js backend either as API routes or you could try the rewrite feature, though I have not tried it with APIs and don't know how it handles things like Authentication HTTP headers.
I have no guidance on the China aspect of this, but...
If use "Next.js in SSG" means `next export
`, then all that is needed is a hosting solution that can serve static files.
If, in contrast, they want `next start
` type behavior in order to get things like ISR as part of their SSG project, then I would be inclined to build the site into a container (see the Docker part of the documentation). With the output of their project being a container image, all they need to find is a hosting provider that can run containers. Nearly all public cloud vendors make it trivial to deploy a web application as a container.
As I said, I don't have any China-specific advice, but I have to assume that there are hosting providers inside China that can do either of the above solutions. The first one might be more feasible, but it does mean losing some of the ISR-like capabilities that you get with an actual Next.js backend.
You're right, I'm wrong. I assumed it pre-rendered the HTML for server rendering and then hydrated it by passing JSON to the client React components.
This doc page says one of the reasons to use getStaticProps is when "the data can be publicly cached". https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
I'm thinking that you likely can't used getStaticProps and protect your site very easily. Next.js likely bundles the code in such a way that only the js for a given page is loaded when the users navigates to that page, but you wouldn't be able to trust that.
So maybe your protected content needs to be loaded from some other endpoint which you can then protect. It could be loaded client-side since you don't care about SEO for this content anyway, and that would still allow you to host your site in a static way.
For for the lack of helpfulness. :)
hey not an expert but maybe I can point you somewhere 🤷♂️ at least with the [postID] question. take with a grain of salt because I don't know everything
pretty much all u wanna know is here
if you use getStaticPaths without a fallback then new posts will hit a 404 because the pages weren't generated at build time
so you need to set a fallback, probably fallback: 'blocking'
, when you return from getStaticPaths. then, when someone makes a request for a post that hasn't been generated, it will generate the page on demand.
the post page won't be generated immediately after the post is created, unless you redirect the post author to the [postID] after it's posted. then it'll be cached and ready to go
then in getStaticProps make sure to enable revalidation so that if a user updates their post it will get re-rendered with the new data the next time the page is requested.
that is a better solution than SSR on every request
Yes, it is possible.
You certainly have to have at least 1 DNS entry (CNAME, usually) to make any subdomain work at all. You could do a wildcard subdomain to keep it at just 1.
You'd then have to some kind of rewrite engine in front of your site to do the translation from subdomain to subfolder. If you are running the real Next.js backend (i.e. you didn't just export a static site), you can do this with Next.js rewrite rules with some regular expressions based on the host header and the request path. Otherwise, you can use something like nginx to do the reverse proxy duties with similar regular expressions.
Keep in mind that your next.js application code will still think it is running in a subfolder, so you'll have some messyness with internal site links.
Generate the details statically, and insert a dynamic
component where you want to display the user-specific data. Access the context from there. This part will be rendered on the client.
See https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
I'm guessing that the component you're trying to import does something with the window object which in SSR is simply not defined. A simple workaround would be Nextjs built-in dynamic import https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
Are you using next/link for each of the links? Without that the page will refresh. Also in next.js 10 you no longer need the “as” prop in case you’re using that.
https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation use getStaticPaths to define the paths should be made at build time
getInitialProps
is no longer recommended since version 9.3
(latest is v11
) in lieu of getServerSideProps
, or ideally getStaticProps
.
Source: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps
Ah, okay. Have you taken a look at these:
Tutorial: https://vercel.com/docs/next.js/incremental-static-regeneration
E-commerce kit: https://nextjs.org/commerce
The e-commerce kit is said to have ISR for its product pages. I would try to download it and deploy it to a test Kubernetes environment. Then, modify it as you please.
Majority of the time you’ll be using npm run dev
. That boots up Next in development mode. It will rebuild the application as you’re coding (Fast refresh).
npm run build
compiles the application as if it were to be published to a production server. This is output into the .next/
folder.
npm run start
serves the built application. It’s essentially the final product. After you run this command any local changes will not be reflected until you run another build and restart it. Not ideal for development and should only be used for final testing or debugging.
This link from the docs explains things well (already posted below).
I would rather consider using a combo of link preload along with the Head component
Depends on your revalidation strategy, you can define the behavior of that exact scenario to either serve the user 5 posts while the page with 6 builds so the next user will get the newly build page or you can make the user wait for the build so you always serve 6.
https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key-required
ISR is more specifically about updating static content once it's been created.
For handling new pages, the key detail is the fallback attribute returned from getStaticPaths https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key-required
not really, its not the name the wildcard, but the double brackets, the name, of course, is mandatory, since it is the name of the params
https://nextjs.org/docs/routing/dynamic-routes#catch-all-routes
here you can find all the docs but just for reference
/post/[[...slug]].tsx
will match:
/post
/post/mypost
/post/2021/05/16/
/post/2021/05/16/mypost
and so on in the [[..slug]].tsx page you would need some logic to elaborate the given params, since /2021/05/16/mypost will be in the slug object
It's hard to tell without seeing the code. It's also worth noting that as of Next v9.3, it's recommended to use getStaticProps
or getServerSideProps
instead if you can upgrade.
you can use chrome devtools and also vscode debugger (if you use vscode) with Nextjs just follow this guide to configure your debug environment https://nextjs.org/docs/advanced-features/debugging
anyway, console.log is usually able to ‘explode ‘ objects and shows their content, type, size and so on
Sound like a textbook use case for Nextjs API Routes. I see no need for custom server.