I was creating a blog with nextjs MongoDB and express. I used getStaticProps and getStaticPaths to generate pages dynamically and display each blog on a separate page. but after deployment, if I add or remove a blog from the API then. it is not reflected on the website until the next deployment.
This is the expected behavior when using Next to build a static site. At build time, it's going to use getStaticPaths to generate a list of all the available pages for your blog, and then it will build each one into an html file using getStaticProps data. From that point forward, getStaticPaths and getStaticProps won't run again (they run in development mode, but not when you build and export your site).
So when you delete or add a blog post, the static website doesn't know anything about that because it's just a "dumb" set of html files. You have generally two options:
Set up a build pipeline that listens for changes (add, remove, update) to your blog content and rebuilds your site when the content changes, or
Switch to using Next in SSR mode instead of SSG mode, which would allow you to use getServerSideProps which runs on every page load and which would update immediately as your content changes.
That second one (using SSR) requires you to run your Next site on a node server like Vercel or Firebase Functions or something similar versus how you have it now (SSG) where it's just a bunch of html files and javascript and can be hosted in places like Github pages or Amazon S3.
Related
I'm learning nextjs and read in some places that nextjs only prerenders the first page and in some other places they say nextjs prerenders all pages by default so I cant understand which one is true
There are different rendering stategies. You can select which one NextJs will choose for each page by adding a method in your page file.
getStaticProps will prerender an HTML file ate the build time, you can still have a useEffect to hydrate the content of the page.
getStaticPath is kinda same but you can prerender differents pages for different routes, or on demand on non existing paths if fallback: 'blocking'is provided
You can also go form ISR (Incremental Static Regeneration), an inbetween Static/SSR, where pages are generated on the demand and cached for the amount of time specified by adding revalidate.
getServerSideProps will render the page on demand
Every one of this rendering strategies have strength and drawbacks, static pages are useful for first render but can need another round trip to hydrate content. Server render is usefull for SEO but can yield to higher server CPU usage.
What is nice is that you can choose which strategy to employ depending on the page you render.
Edit: I did not add it but the principe of these methods is that you fetch data/do stuff in them, and their return statement will be consumed by the page they live in as parameters.
I have a Github repo that has Pages enabled. In Pages, I have an index.js that contains a function. The function is run automatically when you hit an HTTP endpoint. The application is a widget, so it's not like I want to host a whole website. I jsut want to be able to hit an endpoint from a <script> tag and run my code in a third-party site.
The index.js file is created by building my React app with Parcel and compiling it down to a single js file. The file itself runs an IIFE - this is created by Parcel after building and looks something like this:
!function(){function e(e,t,n,r){Object.defineProperty...
// hundreds of lines minified into one humongus line of code
...{domElement:e})}),e)})),Er()}();
For reference, I created it by following this tutorial, and you can see the author's script in their github repo here.
But Github PAges is public, so I wanted to move my script to GCP. I thought a simple Cloud function would do, but I get the dreaded could not handle the request error. For my Cloud Functions app I tried the following:
exports.helloWorld = (req, res) => {
const widget = // copy in all of the above code
res.status(200).send(widget);
}
This threw the above error.
Is there a better/different way to host a single function script like this that runs on http call?
From what I understand, you're simply trying to host a javascript file somewhere where it can be used by other projects. If you're set on Google cloud, you could just upload your javascript file to a public bucket. Unless you want to perform any dynamic logic each time the file is requested, you don't need anything more complicated than a static host.
You mention that you want to use GCP because Github pages is public, but any file you host would be public unless you want to set up rules so that only specific domains can request the file.
Note: I am kind of new to web development so please help me through any misconceptions I might have.
I am trying to learn the MERN stack. As an example, I am trying to make a two page site with a homepage and an about page. I made a ./public folder and added an index.html and an about.html to that folder. Then I started by learning some basic express where I have this line which will let the server serve static files from the ./public folder:
// set static folder
app.use(express.static(path.join(__dirname, 'public', )));
After I felt good about this, I wanted to add React to my existing project. This is where I ran into some confusion. It seems like React doesn't allow multiple pages in my website; I saw this SO post. So, React is good for building single page applications. I also saw this YouTube video where the first three minutes explain the difference between traditional multiple-page applications and React SPAs. He stated that all the pages will be sent at one time and the react-router will intercept any page requests and re-render the browser with the pages it already received on the first page load.
So, finally we get to my question. Going back to my example, suppose my about page is VERY large, with a lot of text and images. Isn't that potentially wasteful if I load the homepage, but the server has to send the entire website including the large about page, even though I might never even click on the about page? Once it is all loaded, I understand that the client has a smooth experience going from one page to the next without having to contact the server. But doesn't it mean that the client experiences long initial wait times. And, isn't this wasting server resources by sending pages the user might never click on. And the problem only seems to get worse the more unique pages the website has.
"He stated that all the pages will be sent at one time and the react-router will intercept any page requests and re-render the browser with the pages it already received on the first page load."
This is an oversimplification that is at the root of your misunderstanding.
Your react app is going to be a small amount of HTML that acts as the document root, and then a fair amount of CSS and JS. This JS React app will execute to generate your pages based on how you have configured your views and wired them to any data model. Generally with a SPA like this, you will load one view at a time, and it will, if applicable, make a request to the server for any data it needs to render, which will generally be returned as JSON. Once the JSON is received, it will get parsed in the browser into the data model and the UI will update to reflect the new state of the data model. Critically, each view (if wired correctly) will only fetch data from the server when the view loads; furthermore, any images or other assets in the UI will only be loaded when the UI renders them, so there will be no prefetching that wastes resources.
Because the react components can basically act as templates, you can actually save bandwidth in this way. Say you had 100 product pages on your site that were identical except for the product information. If you were to serve a new HTML document for each page there would be duplicated bandwidth in the markup sent each time. However, in React you can define a single <ProductPage /> component that will fetch only the product information and load it into the markup template each time, removing the issue of sending duplicate HTML.
There are also additional ways to split up your react app using tricks like lazy loading, to only fetch the salient JS when it is about to be used.
So, no, using a React app does not mean that it fetches all the HTML pages and assets for the site all at once. While one could write a React app in a wasteful manner, most properly structured React apps should be smaller than the rendered totality of the site.
I'm trying to use dynamic routes in a Nuxt SPA. I know how to use dynamic routes in Universal Mode and I know how to generate them during build time using functions but I'm looking for something where I don't need to re-build with every new entry in a database for instance.
My web-app allows users to create content (via Strapi backend) that should be immediately accessible in a form like www.domain.com/content/uniqe_id (without rebuilding the project)
Is this possible? Can I create something like the /content/index.vue that has access to the parameters and fetch the right content?
On a side-note: I would prefer to use Universal Mode for several reasons, but I'm using Three.js in my project and the only way to get it to work is to use SPA. I've posted about it here
If you are using SPA mode, you don't really need to worry about dynamic routes, as everything is rendered on the client. The only thing you would need to take care of, is setting up your production server to always redirect to your index.html, so you don't get a 404 when accessing other pages.
If you are using Universal you could still generate a SPA fallback for handling your dynamic routes on the client side, by adding this to your nuxt.config.js:
Docs
generate: {
fallback: true,
// ...
},
Using this, Nuxt generates a 404.html which will render the page in SPA mode, instead of showing a 404, while the other routes are generated like normal.
If you want to properly generate all routes and have instant access, you could use this technique to show users a temporary SPA version of your page, until the page is rebuilt.
I'm building a simple website generator using React, Express/Node and MongoDB.
I built a UI to receive contents and styling params from a multi-step form, and a dashboard where users can manage settings in second place. All the data is saved/fetched in Mongo when needed, using Express. I have a "publish" button in the frontend, which fires a POST to the backend.
Then the related express route fetches the correct data from mongo and pass it to a function, which runs locally a "create-react-app" with a custom template and injects params/content to the right components. After that, it runs a build and deploys the result to a subdomain.
My question is: am I wrong managing to build static files and deploying them every single time the user hits the "publish" button?
Do I need to dynamically generate and serve the site when is requested?
The best and most "react" way to do this would indeed be to dynamically generate and serve the site. It will be a bit more upfront work but will result in better ux.
What you are doing now will be quite slow and not very user friendly.