{"id":6374,"date":"2020-11-25T16:23:00","date_gmt":"2020-11-25T16:23:00","guid":{"rendered":"https:\/\/azoora.com\/blog\/?p=6374"},"modified":"2021-08-21T17:08:34","modified_gmt":"2021-08-21T17:08:34","slug":"easily-deploy-a-fullstack-next-js-app-with-vercel","status":"publish","type":"post","link":"https:\/\/azoora.com\/blog\/tutorial\/easily-deploy-a-fullstack-next-js-app-with-vercel\/","title":{"rendered":"Easily Deploy a Fullstack Next.js App with Vercel"},"content":{"rendered":"\n<p>With Next.js and Vercel, creating and deploying production-ready web apps has never been easier. It is optimized for running high-performance production workloads and provides a world-class developer experience straight out of the box. Continue reading to learn more about what makes Next.js so appealing to work with and how simple it is to publish your code to production.<\/p>\n\n\n\n<h2>Installation and Setup<\/h2>\n\n\n\n<p>Ensure that &#8220;npm&#8221; is installed on your computer:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>node -v &amp;&amp; npm -v<\/code><\/pre>\n\n\n\n<p>The corresponding version numbers should be printed to the console. If not, you can find installation instructions for your platform from the official <a href=\"https:\/\/nodejs.org\/en\/\">Node.js<\/a> site.<\/p>\n\n\n\n<p>We can use the following command to scaffold out a new Next.js project if we have the node toolchain installed on our machines:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-next-app my-amazing-app<\/code><\/pre>\n\n\n\n<p>Start the development server by going to the directory you just created:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cd my-amazing-app &amp;&amp; npm run dev<\/code><\/pre>\n\n\n\n<p>By default, your app will be served at <a href=\"http:\/\/localhost:3000\/\">localhost:3000<\/a>, and when you visit it with your browser, you&#8217;ll be greeted with the default welcome screen.<\/p>\n\n\n\n<h2>Static Data Fetching<\/h2>\n\n\n\n<p>The &#8220;getStaticProps&#8221; data-fetching hook allows you to provide dynamic data to your pages at build time. This is ideal for marketing pages when data isn&#8217;t updated frequently and speed is a top consideration. Replace the default contents of &#8220;pages\/index.js&#8221; with the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import Head from \"next\/head\";\n\nexport default function Home({\n  title = \"Hello World!\",\n  metaContent = \"Generic SEO pitch\",\n  copy = \"I'm having writer's block.\",\n}) {\n  return (\n    &lt;&gt;\n      &lt;Head&gt;\n        &lt;title&gt;{title}&lt;\/title&gt;\n        &lt;meta content={metaContent} \/&gt;\n      &lt;\/Head&gt;\n      &lt;div&gt;\n        &lt;h1&gt;{title}&lt;\/h1&gt;\n        &lt;p&gt;{copy}&lt;\/p&gt;\n      &lt;\/div&gt;\n    &lt;\/&gt;\n  );\n}\n\nexport const getStaticProps = async () =&gt; {\n  \/\/ This is a full server-side Node environment,\n  \/\/ which means that you can make network requests,\n  \/\/ talk to databases, read from the file-system,\n  \/\/ and do whatever you want to fetch your data.\n\n  return {\n    props: {\n      title: \"My Amazing Startup\",\n      metaContent: \"Amazing SEO poetry\",\n      copy:\n        \"I'm in the business of making people smile. That's all I'm here for.\",\n    },\n  };\n};<\/code><\/pre>\n\n\n\n<p>Everything is the same as it is in any other React project, with a few exceptions. First, you&#8217;ll see that we&#8217;re not explicitly importing React because Next.js includes it by default. Next, you can see that we&#8217;re able to set our page metadata from the\u00a0&#8220;<code>&lt;Head \/><\/code>&#8221;\u00a0component and don&#8217;t need to bring in another third-party library like <a href=\"https:\/\/www.npmjs.com\/package\/react-helmet\">react-helmet<\/a>. Finally, we&#8217;ve included a &#8220;getStaticProps&#8221; function that returns a props object with the title, &#8220;metaContent&#8221;, and &#8220;copy&#8221; keys. As a result, we can de-structure those props from our top-level page component and read them in. For good measure, we&#8217;ve included default values in case the props aren&#8217;t supplied. These props are baked immediately into your pages with no runtime overhead when your Next.js project is constructed, resulting in enhanced performance and stability.<\/p>\n\n\n\n<h2>Incremental Static Regeneration<\/h2>\n\n\n\n<p>Next. The distinction between static and dynamic is blurred by JavaScript. Just because your data is statically fetched doesn&#8217;t imply you&#8217;ll be stuck with it until you re-deploy. Incremental Static Regeneration allows you to refresh existing pages as traffic comes in by re-rendering them in the background. Simply append the &#8220;revalidate&#8221; key to the object returned by the &#8220;getStaticProps&#8221; function, along with the number of seconds you want to wait before revalidating and recreating the page if data changes. You might not notice a change in our somewhat contrived local example, but it will come to life once you start accessing data from a database or CMS.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export const getStaticProps = async () =&gt; {\n  return {\n    props: {\n      title: \"My Amazing Startup\",\n      copy:\n        \"I'm in the business of making people smile. That's all I'm here for.\",\n    },\n    revalidate: 1, \/\/ number of seconds to wait before revalidating\n  };\n};<\/code><\/pre>\n\n\n\n<h2>Server Side Rendering<\/h2>\n\n\n\n<p>You may have very dynamic material that needs to update based on a variety of factors. Perhaps you&#8217;d like to look at the request headers of incoming traffic to see how you want to render your page. Next.js provides the &#8220;getServerSideProps&#8221; function for this purpose, which is similar to the &#8220;getStaticProps&#8221; function we&#8217;ve already seen.<\/p>\n\n\n\n<p>Create a new file in your &#8220;pages&#8221; directory called &#8220;hello-user-agent.js&#8221; with the following contents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import Head from \"next\/head\";\n\nexport default function HelloUserAgent({ userAgent = \"Nobody\" }) {\n  return (\n    &lt;&gt;\n      &lt;Head&gt;\n        &lt;title&gt;Hello User Agent!&lt;\/title&gt;\n      &lt;\/Head&gt;\n      &lt;p&gt;\n        {\" \"}\n        Hi &lt;em&gt;{userAgent}&lt;\/em&gt; !{\" \"}\n      &lt;\/p&gt;\n    &lt;\/&gt;\n  );\n}\n\nexport const getServerSideProps = async ({ req }) =&gt; {\n  return {\n    props: {\n      userAgent: req.headers&#91;\"user-agent\"],\n    },\n  };\n};<\/code><\/pre>\n\n\n\n<p>This page has a structure identical to our &#8220;index.js&#8221; home page, but with one minor modification. We are exposing a function named &#8220;getServerSideProps&#8221; instead of a &#8220;getStaticProps&#8221; function below our page component. Notice how we&#8217;ve destructed a Node.js <a href=\"https:\/\/nodejs.org\/api\/http.html#http_class_http_incomingmessage\">HTTP Incoming Message<\/a> object and read values from it in the body of our function. This page is totally rendered in a server environment using a lightweight <a href=\"https:\/\/vercel.com\/docs\/serverless-functions\/introduction#\">Serverless Function<\/a>, which gives your page new props every time it&#8217;s requested. You&#8217;ll see your browser&#8217;s user agent string printed on the screen if you go to &#8220;localhost:3000\/hello-user-agent&#8221;.<\/p>\n\n\n\n<p>It&#8217;s worth noting that rendering a page in this manner has a tiny performance penalty. It can take a few moments (500-800 ms on average) for the function that renders your page to start up if it hasn&#8217;t been used in a few minutes. The <a href=\"https:\/\/mikhail.io\/serverless\/coldstarts\/define\/\">cold start<\/a> problem is what this is known as. This difficulty can be mitigated with a good <a href=\"https:\/\/vercel.com\/blog\/serverless-pre-rendering#cache-control-%60stale-while-revalidate%60\">caching approach<\/a>.<\/p>\n\n\n\n<h2>API Routes<\/h2>\n\n\n\n<p>API Routes let you design HTTP request handlers with the same file-system routing structure as the frontend. When we used &#8220;create-next-app&#8221; to create our project, an API route was built for us at &#8220;pages\/api\/hello.js&#8221; with the following contents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export default (req, res) =&gt; {\n  res.statusCode = 200\n  res.json({ name: 'John Doe' })\n}<\/code><\/pre>\n\n\n\n<p>The function will produce a JSON response if you browse to <a href=\"http:\/\/localhost:3000\/api\/hello\">localhost:3000\/api\/hello<\/a>. API Routes are useful for connecting to a database rapidly and delivering results, as well as processing forms and sending emails.<\/p>\n\n\n\n<h2>Deploy to Vercel<\/h2>\n\n\n\n<p>Now that we&#8217;ve got a feel for how Next.js works, we need a way to get it up on the internet. Vercel is a deployment platform for frontend projects made by the same people that created Next.js, so its only natural that the deployment experience feels as simple as the development experience.<\/p>\n\n\n\n<p>Create a new git repository and push it to a Git provider to get started. After you&#8217;ve created a URL for your repository, go to <a href=\"https:\/\/deploy.new\/%3Cyour-repo-url\">https:\/\/deploy.new\/<\/a> to begin the import process. A new account will be created for you if you don&#8217;t already have one, and a deployment will be made to your account. It&#8217;s as simple as that! The <a href=\"https:\/\/vercel.com\/edge-network\">Vercel Edge Network<\/a> distributes your Next.js project all over the world. Every time you push changes or create a new branch, your URL will be updated and a new deployment will be created for you. The Vercel platform&#8217;s <a href=\"https:\/\/vercel.com\/docs\">documentation<\/a> might help you learn more about it.<\/p>\n\n\n\n<p>Although the Git workflow is great for iterating on a production app, you may utilize the <a href=\"https:\/\/vercel.com\/download\">Vercel CLI<\/a> to make a deployment by running the &#8220;vercel&#8221; command from your project root.<\/p>\n\n\n\n<h2>Final Thoughts<\/h2>\n\n\n\n<p>Next.js is a robust framework for projects of any size, although it hides a lot of the finer points and emphasizes minimalism. It has a hybrid rendering strategy that allows you to choose whether you want static markup with pre-populated props supplied at build time or server-rendered pages with dynamic data requirements for each request on a per-page basis. API routes make it easier to set up a backend without having to use Express or other API frameworks. We&#8217;ve gone through the most important aspects of Next.js, but we&#8217;ve only scratched the surface. To learn more, see the <a href=\"https:\/\/nextjs.org\/docs\/getting-started\">official documents<\/a> and check out the <a href=\"https:\/\/nextjs.org\/learn\/basics\/create-nextjs-app\">interactive learning tutorial<\/a> for creating your own blog from the ground up!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>With Next.js and Vercel, creating and deploying production-ready web apps has never been easier. It is optimized for running high-performance production workloads and provides a world-class developer experience straight out of the box. Continue reading to learn more about what makes Next.js so appealing to work with and how simple it is to publish your [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":6375,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[145,77,62],"tags":[146,73,110],"jetpack_featured_media_url":"https:\/\/azoora.com\/blog\/wp-content\/uploads\/2021\/08\/easily-deloy-a-next.js-app-with-vercel.png","jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/p7FQPL-1EO","jetpack-related-posts":[],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts\/6374"}],"collection":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/comments?post=6374"}],"version-history":[{"count":1,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts\/6374\/revisions"}],"predecessor-version":[{"id":6376,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts\/6374\/revisions\/6376"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/media\/6375"}],"wp:attachment":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/media?parent=6374"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/categories?post=6374"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/tags?post=6374"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}