<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AllDevUtils on Medium]]></title>
        <description><![CDATA[Stories by AllDevUtils on Medium]]></description>
        <link>https://medium.com/@alldevutils?source=rss-618119d9248c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aED-b0QUiQP82X_kTu5Thg.png</url>
            <title>Stories by AllDevUtils on Medium</title>
            <link>https://medium.com/@alldevutils?source=rss-618119d9248c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:52:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alldevutils/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build a Blog Website with Next.js — Part 2(Backend)]]></title>
            <link>https://javascript.plainenglish.io/build-a-blog-website-with-next-js-part-2-backend-357573807016?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/357573807016</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 20:26:16 GMT</pubDate>
            <atom:updated>2023-04-15T20:26:16.378Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Blog Website with Next.js — Part 2(Backend)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HihwBkgk6rsKse7eBUmyOg.png" /><figcaption>(AllDevUtils Originals)</figcaption></figure><p>In the first article of this series, we created a simple blog website using Next.js and Tailwind CSS, and implemented the frontend components for displaying blog posts and creating new posts through an admin panel. In this second article, we will focus on the backend implementation of the blog website, including the MongoDB database and the API endpoints.</p><p><a href="https://medium.com/@alldevutils/blog-website-with-next-js-part-1-frontend-f0da2dbfbd3d">Blog Website with Next.js — Part 1 (Frontend)</a></p><h3>Setting up the MongoDB Database</h3><p>To store the blog posts, we will be using the MongoDB database. You can create a free account on MongoDB Atlas, which provides a fully managed cloud database service for MongoDB. Once you have created an account and logged in to the dashboard, follow these steps to create a new database:</p><ol><li>Click on the “Create a New Project” button and give your project a name.</li><li>Click on the “Build a Cluster” button and select the free tier.</li><li>Choose the region closest to you and click on “Create Cluster”.</li><li>Wait for the cluster to be created, which may take a few minutes.</li><li>Once the cluster is created, click on “Connect”.</li><li>Choose “Connect Your Application” and select the driver and version you are using. You can also generate a connection string with the required parameters.</li><li>Copy the connection string and replace &lt;password&gt; with the password for the database user you created. You can create a new user by clicking on &quot;Database Access&quot; and &quot;Add New Database User&quot;.</li><li>Create a .env.local file in the root folder of your project and add the following line:</li></ol><pre>MONGODB_URI=&lt;your-connection-string&gt;</pre><p>This will allow us to connect to the database using the MONGODB_URI environment variable.</p><p>Next, we will create a utility function that connects to the MongoDB database and returns a reference to the db object.</p><h3>Connecting to the MongoDB Database</h3><p>Create a new file named mongodb.js in the utils folder, and add the following code:</p><pre>import { MongoClient } from &#39;mongodb&#39;<br><br>const client = new MongoClient(process.env.MONGODB_URI, {<br>  useNewUrlParser: true,<br>  useUnifiedTopology: true,<br>})<br><br>export async function connectToDatabase() {<br>  if (!client.isConnected()) await client.connect()<br>  const db = client.db(&#39;blog&#39;)<br>  return { db, client }<br>}</pre><p>This code imports the MongoClient class from the mongodb package, creates a new client object with the connection string specified in the MONGODB_URI environment variable, and exports a connectToDatabase function that connects to the database and returns a reference to the db object. The function also caches the client object to improve performance by avoiding redundant connections.</p><h3>Creating API Endpoints</h3><p>Next, we will create two API endpoints that allow us to retrieve a list of blog posts and create new posts.</p><p>Create a new file named posts.js in the pages/api folder, and add the following code:</p><pre>import { connectToDatabase } from &#39;../../utils/mongodb&#39;<br><br>export default async function handler(req, res) {<br>  const { method } = req<br><br>  if (method === &#39;GET&#39;) {<br>    const { db } = await connectToDatabase()<br>    const posts = await db.collection(&#39;posts&#39;).find().sort({ date: -1 }).toArray()<br>    res.status(200).json(posts)<br>  } else if (method === &#39;POST&#39;) {<br>    const { db } = await connectToDatabase()<br>    const { title, content } = req.body<br>    const date = new Date().toISOString()<br>    const result = await db.collection(&#39;posts&#39;).insertOne({ title, content, date })<br>    res.status(201).json(result.ops[0])<br>  } else {<br>    res.status(400).json({ message: &#39;Method not allowed&#39; })<br>  }<br>}</pre><p>The handler function is an asynchronous function that takes a req (request) and res (response) object as parameters. The method property of the request object is used to determine whether the request is a GET or POST request.</p><p>In the case of a GET request, the function calls the connectToDatabase function to connect to the MongoDB database and retrieve all the blog posts, sorted by date in descending order. The posts are then sent back to the client as a JSON response with a status code of 200.</p><p>In the case of a POST request, the function extracts the title and content properties from the request body, generates a new date, and inserts the new post into the posts collection in the database. The new post object is then sent back to the client as a JSON response with a status code of 201.</p><p>If the request method is neither GET nor POST, the function returns a JSON response with a status code of 400, indicating that the request method is not allowed.</p><h3>Fetching Blog Posts in the Frontend</h3><p>Now that we have created the API endpoints, we can fetch the blog posts from the frontend using the fetch function.</p><p>Open the pages/index.js file and add the following code:</p><pre>import Head from &#39;next/head&#39;<br>import Link from &#39;next/link&#39;<br><br>export default function Home({ posts }) {<br>  return (<br>    &lt;div className=&quot;max-w-3xl mx-auto px-4 sm:px-6 lg:px-8&quot;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Blog&lt;/title&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br><br>      &lt;header className=&quot;py-6&quot;&gt;<br>        &lt;nav className=&quot;flex justify-between items-center&quot;&gt;<br>          &lt;div className=&quot;text-xl font-bold&quot;&gt;<br>            &lt;Link href=&quot;/&quot;&gt;<br>              &lt;a&gt;Blog&lt;/a&gt;<br>            &lt;/Link&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Link href=&quot;/admin&quot;&gt;<br>              &lt;a className=&quot;border-2 border-gray-700 px-4 py-2 rounded-lg text-sm font-medium&quot;&gt;<br>                Admin<br>              &lt;/a&gt;<br>            &lt;/Link&gt;<br>          &lt;/div&gt;<br>        &lt;/nav&gt;<br>      &lt;/header&gt;<br><br>      &lt;main&gt;<br>        &lt;div className=&quot;grid gap-8 md:grid-cols-2 lg:grid-cols-3&quot;&gt;<br>          {posts.map((post) =&gt; (<br>            &lt;div key={post._id} className=&quot;border border-gray-200 rounded-lg overflow-hidden&quot;&gt;<br>              &lt;div className=&quot;bg-gray-100 px-4 py-2 font-medium&quot;&gt;<br>                &lt;Link href={`/posts/${post._id}`}&gt;<br>                  &lt;a&gt;{post.title}&lt;/a&gt;<br>                &lt;/Link&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;p-4&quot;&gt;{post.content}&lt;/div&gt;<br>              &lt;div className=&quot;bg-gray-100 px-4 py-2 text-sm text-gray-500&quot;&gt;<br>                {new Date(post.date).toLocaleDateString()}<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export async function getStaticProps() {<br>  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/posts`)<br>  const posts = await res.json()<br>  return { props: { posts } }<br>}</pre><p>This code imports the Head and Link components from Next.js, and defines a new Home component that renders the list of blog posts.</p><p>The Home component receives a posts prop, which is an array of blog post objects that we will fetch from the API using the getStaticProps function. The function uses the fetch function to send a GET request to the /api/posts endpoint, and retrieves the list of posts as a JSON response. The posts prop is then passed to the Home component, and used to render a grid of blog post cards.</p><p>Each blog post card displays the title, content, and date of the post. The title is a link that takes the user to the individual post page, which we will create next.</p><h3>Creating Individual Post Pages</h3><p>To create individual post pages, we need to create a new dynamic route that matches URLs that start with /posts/ and end with the post ID.</p><p>Create a new file called pages/posts/[id].js and add the following code:</p><pre>import Head from &#39;next/head&#39;<br>import Link from &#39;next/link&#39;<br><br>export default function Post({ post }) {<br>  return (<br>    &lt;div className=&quot;max-w-3xl mx-auto px-4 sm:px-6 lg:px-8&quot;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;{post.title}&lt;/title&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br><br>      &lt;header className=&quot;py-6&quot;&gt;<br>        &lt;nav className=&quot;flex justify-between items-center&quot;&gt;<br>          &lt;div className=&quot;text-xl font-bold&quot;&gt;<br>            &lt;Link href=&quot;/&quot;&gt;<br>              &lt;a&gt;Blog&lt;/a&gt;<br>            &lt;/Link&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Link href=&quot;/admin&quot;&gt;<br>              &lt;a className=&quot;border-2 border-gray-700 px-4 py-2 rounded-lg text-sm font-medium&quot;&gt;<br>                Admin<br>              &lt;/a&gt;<br>            &lt;/Link&gt;<br>          &lt;/div&gt;<br>        &lt;/nav&gt;<br>      &lt;/header&gt;<br><br>      &lt;main&gt;<br>        &lt;article&gt;<br>          &lt;h1 className=&quot;text-4xl font-bold mb-4&quot;&gt;{post.title}&lt;/h1&gt;<br>          &lt;div className=&quot;text-gray-500 mb-4&quot;&gt;<br>            {new Date(post.date).toLocaleDateString()}<br>          &lt;/div&gt;<br>          &lt;div dangerouslySetInnerHTML={{ __html: post.content }} /&gt;<br>        &lt;/article&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export async function getStaticPaths() {<br>  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/posts`)<br>  const posts = await res.json()<br><br>  const paths = posts.map((post) =&gt; ({<br>    params: { id: post._id },<br>  }))<br><br>  return { paths, fallback: false }<br>}<br><br>export async function getStaticProps({ params }) {<br>  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/posts/${params.id}`)<br>  const post = await res.json()<br><br>  return { props: { post } }<br>}</pre><p>This code defines a new Post component that receives a post prop, which is an object that represents a single blog post.</p><p>The Post component uses the Head and Link components to set the page title and navigation links. It then renders the post title, date, and content using HTML markup.</p><p>The getStaticPaths function retrieves the list of all blog posts from the API and generates a list of paths that matches the URL format for individual post pages. Each path is an object with a params property that contains the post ID. The fallback property is set to false, which means that Next.js will pre-render only the paths that are explicitly defined in the paths array.</p><p>The getStaticProps function retrieves the blog post data from the API using the post ID passed as a parameter. The post data is then returned as a prop to the Post component.</p><p><a href="https://blog.devgenius.io/advanced-next-js-concepts-8439a8752597">Advanced Next.js Concepts</a></p><h3>Conclusion</h3><p>In this article, we have built a simple blog website using Next.js, Tailwind CSS, and MongoDB. We have created a custom API to store and retrieve blog post data, and used Next.js to pre-render the frontend pages with dynamic routing to create individual blog post pages. We have also used Tailwind CSS to style the UI and create responsive layout.</p><p>This blog website is just a starting point, and there are many ways to extend and customize it. Here are a few ideas to get you started:</p><ul><li>Add authentication and authorization to allow only authorized users to create, edit, and delete blog posts.</li><li>Add comments and social sharing functionality to the blog posts.</li><li>Implement pagination to limit the number of posts displayed on the home page.</li><li>Add search functionality to allow users to search for specific blog posts.</li><li>Use server-side rendering (SSR) or incremental static regeneration (ISR) to improve performance and SEO.</li></ul><p>Next.js and Tailwind CSS provide a solid foundation for building scalable and maintainable web applications. With the power of MongoDB and the flexibility of custom API routes, the possibilities are endless.</p><p>I hope this article has been helpful in getting started with building your own blog website using Next.js, Tailwind CSS, and MongoDB. Happy coding!</p><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=357573807016" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/build-a-blog-website-with-next-js-part-2-backend-357573807016">Build a Blog Website with Next.js — Part 2(Backend)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Blog Website with Next.js — Part 1 (Frontend)]]></title>
            <link>https://javascript.plainenglish.io/blog-website-with-next-js-part-1-frontend-f0da2dbfbd3d?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0da2dbfbd3d</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[next]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 11:49:13 GMT</pubDate>
            <atom:updated>2023-04-15T20:25:52.599Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Blog Website with Next.js — Part 1 (Frontend)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRvzrm0eKOqgeReE_v2LQw.png" /><figcaption>(AllDevUtils Originals)</figcaption></figure><p>In this article, we’ll be building the frontend of a blog website using Next.js and Tailwind CSS. Next.js is a popular React-based framework that offers server-side rendering, static site generation, and other features that make building scalable web applications easier. Tailwind CSS is a utility-first CSS framework that lets you style your components quickly and efficiently.</p><p>By the end of this article, you’ll have a working blog website with a homepage that lists recent posts, and a post page that shows the details of a single post along with a comment section.</p><h3>Setting up the Project</h3><p>To get started, we’ll need to install Next.js and create a new project. You can do this by running the following commands in your terminal:</p><pre>npx create-next-app my-blog<br>cd my-blog</pre><p>Next, we’ll add Tailwind CSS to the project. You can do this by running the following command in your terminal:</p><pre>npm install tailwindcss</pre><p>Once installed, we need to configure Tailwind CSS to work with Next.js. We’ll do this by creating a tailwind.config.js file in the root of our project, and adding the following configuration:</p><pre>// tailwind.config.js<br>module.exports = {<br>  mode: &#39;jit&#39;,<br>  purge: [<br>    &#39;./pages/**/*.{js,ts,jsx,tsx}&#39;,<br>    &#39;./components/**/*.{js,ts,jsx,tsx}&#39;,<br>  ],<br>  theme: {<br>    extend: {},<br>  },<br>  variants: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><p>This configuration sets up Tailwind CSS to work in jit mode, which improves build times, and sets up PurgeCSS to remove any unused CSS from our build output.</p><h3>Building the Layout</h3><p>Now that we have our project set up with Next.js and Tailwind CSS, let’s start building our layout. We’ll begin by creating a layout component that contains a header, footer, and main content area.</p><p>Create a new file called Layout.js in the components folder, and add the following code:</p><pre>// components/Layout.js<br>import React from &#39;react&#39;<br><br>const Layout = ({ children }) =&gt; {<br>  return (<br>    &lt;div className=&quot;flex flex-col min-h-screen&quot;&gt;<br>      &lt;header className=&quot;bg-gray-800 text-white py-4&quot;&gt;<br>        &lt;div className=&quot;container mx-auto px-4&quot;&gt;<br>          &lt;h1 className=&quot;text-3xl font-bold&quot;&gt;My Blog&lt;/h1&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br>      &lt;main className=&quot;flex-grow container mx-auto px-4 py-8&quot;&gt;<br>        {children}<br>      &lt;/main&gt;<br>      &lt;footer className=&quot;bg-gray-800 text-white py-4&quot;&gt;<br>        &lt;div className=&quot;container mx-auto px-4 text-center&quot;&gt;<br>          &amp;copy; 2023 My Blog<br>        &lt;/div&gt;<br>      &lt;/footer&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default Layout</pre><p>This code defines a Layout component that uses the min-h-screen class to make sure it takes up the entire height of the screen, and contains a header, main content area, and footer. The header and footer have a black background and white text, while the main content area is white.</p><p>Now, let’s build the homepage. Create a new file called index.js in the pages folder, and add the following code:</p><pre>// pages/index.js<br>import React from &#39;react&#39;<br>import Layout from &#39;../components/Layout&#39;<br><br>const IndexPage = () =&gt; {<br>  return (<br>    &lt;Layout&gt;<br>      &lt;div className=&quot;space-y-8&quot;&gt;          <br>          &lt;h2 className=&quot;text-2xl font-bold&quot;&gt;Recent Posts&lt;/h2&gt;<br>          &lt;ul className=&quot;space-y-4&quot;&gt;<br>            &lt;li&gt;<br>              &lt;a href=&quot;/posts/1&quot;&gt;<br>                &lt;h3 className=&quot;text-xl font-bold&quot;&gt;First Post&lt;/h3&gt;<br>                &lt;p className=&quot;text-gray-500&quot;&gt;Lorem ipsum dolor sit amet&lt;/p&gt;<br>              &lt;/a&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>              &lt;a href=&quot;/posts/2&quot;&gt;<br>                &lt;h3 className=&quot;text-xl font-bold&quot;&gt;Second Post&lt;/h3&gt;<br>                &lt;p className=&quot;text-gray-500&quot;&gt;Consectetur adipiscing elit&lt;/p&gt;<br>              &lt;/a&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>              &lt;a href=&quot;/posts/3&quot;&gt;<br>                &lt;h3 className=&quot;text-xl font-bold&quot;&gt;Third Post&lt;/h3&gt;<br>                &lt;p className=&quot;text-gray-500&quot;&gt;Sed do eiusmod tempor incididunt&lt;/p&gt;<br>              &lt;/a&gt;<br>            &lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/Layout&gt;<br>  )<br>}<br><br>export default IndexPage</pre><p>This code defines an IndexPage component that uses the Layout component we defined earlier. It displays a list of recent blog posts with a link to each post page.</p><p>Let’s now create the post page. Create a new file called post/[id].js in the pages folder, and add the following code:</p><pre>// pages/post/[id].js<br>import React from &#39;react&#39;<br>import Layout from &#39;../../components/Layout&#39;<br><br>const PostPage = ({ post }) =&gt; {<br>  return (<br>    &lt;Layout&gt;<br>      &lt;article&gt;<br>        &lt;h1 className=&quot;text-3xl font-bold mb-4&quot;&gt;{post.title}&lt;/h1&gt;<br>        &lt;p className=&quot;text-gray-500 mb-8&quot;&gt;{post.date}&lt;/p&gt;<br>        &lt;div className=&quot;prose&quot; dangerouslySetInnerHTML={{ __html: post.content }}&gt;&lt;/div&gt;<br>      &lt;/article&gt;<br>      &lt;hr className=&quot;my-8&quot; /&gt;<br>      &lt;section&gt;<br>        &lt;h2 className=&quot;text-2xl font-bold mb-4&quot;&gt;Comments&lt;/h2&gt;<br>        &lt;form&gt;<br>          &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt;<br>          &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; required className=&quot;w-full border border-gray-300 py-2 px-3 rounded-lg mb-4&quot; /&gt;<br>          &lt;label htmlFor=&quot;comment&quot;&gt;Comment&lt;/label&gt;<br>          &lt;textarea id=&quot;comment&quot; name=&quot;comment&quot; required className=&quot;w-full border border-gray-300 py-2 px-3 rounded-lg mb-4&quot;&gt;&lt;/textarea&gt;<br>          &lt;button type=&quot;submit&quot; className=&quot;bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/section&gt;<br>    &lt;/Layout&gt;<br>  )<br>}<br><br>export default PostPage</pre><p>This code defines a PostPage component that also uses the Layout component. It displays the title, date, and content of a single blog post, and includes a comment section at the bottom.</p><h3>Adding Functionality</h3><p>Now that we have our layout and pages set up, let’s add some functionality to our blog website. We’ll begin by adding navigation between pages.</p><p>To do this, we’ll create a Navigation component that contains links to the homepage and the admin panel. Create a new file called Navigation.js in the components folder, and add the following code:</p><pre>// components/Navigation.js<br>import React from &#39;react&#39;<br>import Link from &#39;next/link&#39;<br><br>const Navigation = () =&gt; {<br>  return (<br>    &lt;nav className=&quot;bg-gray-700 text-white py-4&quot;&gt;<br>      &lt;div className=&quot;container mx-auto px-4 flex justify-between&quot;&gt;<br>        &lt;Link href=&quot;/&quot;&gt;<br>          &lt;a className=&quot;text-lg font-bold&quot;&gt;My Blog&lt;/a&gt;<br>        &lt;/Link&gt;<br>        &lt;Link href=&quot;/admin&quot;&gt;<br>          &lt;a className=&quot;text-lg font-bold&quot;&gt;Admin&lt;/a&gt;<br>        &lt;/Link&gt;<br>      &lt;/div&gt;<br>    &lt;/nav&gt;<br>  )<br>}<br><br>export default Navigation</pre><p>This code defines a Navigation component that contains two links: one to the homepage, and one to the admin panel.</p><p>Now let’s add some functionality to the admin panel. We’ll begin by creating a form to add new blog posts. Create a new file called admin/index.js in the pages folder, and add the following code:</p><pre>// pages/admin/index.js<br>import React, { useState } from &#39;react&#39;<br>import Layout from &#39;../../components/Layout&#39;<br><br>const AdminPage = () =&gt; {<br>  const [title, setTitle] = useState(&#39;&#39;)<br>  const [content, setContent] = useState(&#39;&#39;)<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault()<br><br>    const response = await fetch(&#39;/api/posts&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>      },<br>      body: JSON.stringify({ title, content })<br>    })<br><br>    if (response.ok) {<br>      setTitle(&#39;&#39;)<br>      setContent(&#39;&#39;)<br>      alert(&#39;Post created!&#39;)<br>    } else {<br>      alert(&#39;Error creating post!&#39;)<br>    }<br>  }<br><br>  return (<br>    &lt;Layout&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;div className=&quot;mb-4&quot;&gt;<br>          &lt;label htmlFor=&quot;title&quot; className=&quot;block font-bold mb-2&quot;&gt;Title&lt;/label&gt;<br>          &lt;input type=&quot;text&quot; id=&quot;title&quot; name=&quot;title&quot; value={title} onChange={(e) =&gt; setTitle(e.target.value)} className=&quot;w-full border border-gray-300 py-2 px-3 rounded-lg&quot; /&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;mb-4&quot;&gt;<br>          &lt;label htmlFor=&quot;content&quot; className=&quot;block font-bold mb-2&quot;&gt;Content&lt;/label&gt;<br>          &lt;textarea id=&quot;content&quot; name=&quot;content&quot; value={content} onChange={(e) =&gt; setContent(e.target.value)} className=&quot;w-full border border-gray-300 py-2 px-3 rounded-lg&quot;&gt;&lt;/textarea&gt;<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot; className=&quot;bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600&quot;&gt;Create Post&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/Layout&gt;<br>  )<br>}<br><br>export default AdminPage</pre><p>This code defines an AdminPage component that uses the Layout component we defined earlier. It displays a form to create new blog posts, and includes a handleSubmit function that sends a POST request to the /api/posts endpoint to create a new post.</p><p>Now let’s create the API endpoint to handle creating new blog posts. Create a new file called posts.js in the pages/api folder, and add the following code:</p><pre>// pages/api/posts.js<br>import { connectToDatabase } from &#39;../../utils/mongodb&#39;<br><br>export default async function handler(req, res) {<br>  const { db } = await connectToDatabase()<br><br>  if (req.method === &#39;POST&#39;) {<br>    const { title, content } = req.body<br><br>    const result = await db.collection(&#39;posts&#39;).insertOne({<br>      title,<br>      content,<br>      date: new Date().toISOString()<br>    })<br><br>    res.status(201).json(result.ops[0])<br>  } else {<br>    res.status(400).json({ message: &#39;Method not allowed&#39; })<br>  }<br>}</pre><p>This code defines an API endpoint that connects to the MongoDB database, and allows for the creation of new blog posts through a POST request. The endpoint extracts the title and content from the request body, inserts them into a new document in the posts collection of the database, and returns the newly created document as a JSON response.</p><p>Finally, we need to display the list of blog posts on the homepage. Update the index.js file in the pages folder with the following code:</p><pre>// pages/index.js<br>import React from &#39;react&#39;<br>import Layout from &#39;../components/Layout&#39;<br>import { connectToDatabase } from &#39;../utils/mongodb&#39;<br><br>const Home = ({ posts }) =&gt; {<br>  return (<br>    &lt;Layout&gt;<br>      &lt;div className=&quot;container mx-auto px-4&quot;&gt;<br>        &lt;h1 className=&quot;text-3xl font-bold mb-4&quot;&gt;Latest Posts&lt;/h1&gt;<br>        {posts.map(post =&gt; (<br>          &lt;div key={post._id} className=&quot;border border-gray-300 rounded-lg mb-4 p-4&quot;&gt;<br>            &lt;h2 className=&quot;text-lg font-bold&quot;&gt;{post.title}&lt;/h2&gt;<br>            &lt;p className=&quot;text-gray-600&quot;&gt;{new Date(post.date).toLocaleDateString()}&lt;/p&gt;<br>            &lt;p&gt;{post.content}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/Layout&gt;<br>  )<br>}<br><br>export async function getServerSideProps() {<br>  const { db } = await connectToDatabase()<br><br>  const posts = await db<br>    .collection(&#39;posts&#39;)<br>    .find({})<br>    .sort({ date: -1 })<br>    .toArray()<br><br>  return {<br>    props: {<br>      posts: JSON.parse(JSON.stringify(posts))<br>    }<br>  }<br>}<br><br>export default Home</pre><p>This code defines the Home component, which displays a list of blog posts fetched from the database using the getServerSideProps function. The function connects to the MongoDB database using the connectToDatabase utility function we defined earlier, and returns an array of posts sorted by date in descending order.</p><h3>Conclusion</h3><p>With these changes in place, you should now have a working blog website that allows you to create new posts using the admin panel, and displays them on the homepage. You can customize the appearance of the website by modifying the Tailwind CSS styles and adding additional components as needed.</p><p>Congratulations, you have completed the first article in the series! In the second article, we will focus on the backend implementation of the blog website, including the MongoDB database and the API endpoints.</p><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em> community and follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em> and</em><strong><em> </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Learn how to build awareness and adoption for your startup with </em></strong><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0da2dbfbd3d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/blog-website-with-next-js-part-1-frontend-f0da2dbfbd3d">Build a Blog Website with Next.js — Part 1 (Frontend)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Next.js Concepts]]></title>
            <link>https://blog.devgenius.io/advanced-next-js-concepts-8439a8752597?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8439a8752597</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[advanced-javascript]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 16:49:56 GMT</pubDate>
            <atom:updated>2023-04-08T08:10:10.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjwgmnEHqoCa7U8SqKiU-A.png" /></figure><p>As a developer, you may have built a Next.js application using the basic concepts such as creating and navigating pages, <a href="https://medium.com/@alldevutils/server-side-rendering-and-data-fetching-3198dc605113">handling data with <strong><em>getStaticProps</em></strong> and <strong><em>getServerSideProps</em></strong></a>, and <a href="https://medium.com/@alldevutils/styling-in-next-js-866ede8d7ab6"><strong><em>styling with CSS modules</em></strong> and <strong><em>styled components</em></strong></a>. However, there are many advanced Next.js concepts that can help you build more complex and powerful applications. In this article, we’ll cover some of these advanced concepts and provide code examples to demonstrate how to use them.</p><p><a href="https://medium.com/@alldevutils/introduction-to-next-js-b3cf00ddd6f1">Introduction to Next.js</a></p><h3>1. Handling Authentication in Next.js</h3><p>Authentication is a critical aspect of web applications that require users to sign in and access their personal data. Next.js provides several authentication strategies that you can use to secure your application. One of the most common approaches is to use cookies to store authentication tokens.</p><p>To implement authentication with cookies in Next.js, you can create an API route that handles user authentication. Here’s an example:</p><pre>// pages/api/login.js<br>import { setCookie } from &#39;nookies&#39;;<br><br>export default function handler(req, res) {<br>  // Check user credentials<br>  const user = authenticateUser(req.body.username, req.body.password);<br>  if (!user) {<br>    res.status(401).send(&#39;Invalid credentials&#39;);<br>    return;<br>  }<br><br>  // Set authentication cookie<br>  setCookie({ res }, &#39;auth_token&#39;, user.auth_token, {<br>    maxAge: 30 * 24 * 60 * 60,<br>    path: &#39;/&#39;,<br>  });<br><br>  // Redirect to dashboard page<br>  res.redirect(&#39;/dashboard&#39;);<br>}</pre><p>In this example, we’re using the nookies library to set a cookie called auth_token with a maximum age of 30 days. Once the user is authenticated, we redirect them to the dashboard page.</p><blockquote>Also, one can use <a href="https://next-auth.js.org/getting-started/introduction"><strong>NextAuth.js</strong></a> for better security purposes.</blockquote><h3>2. Serverless Functions in Next.js</h3><p>Serverless functions are a great way to implement backend functionality without having to manage a server. Next.js provides built-in support for serverless functions using the api directory.</p><p>To create a serverless function in Next.js, create a file in the pages/api directory with the following format:</p><pre>// pages/api/hello.js<br>export default function handler(req, res) {<br>  res.status(200).json({ message: &#39;Hello, world!&#39; });<br>}</pre><p>This function will respond to requests to /api/hello with a JSON message.</p><p>You can also use serverless functions to handle data from forms or other input fields. Here’s an example of a serverless function that handles a form submission:</p><pre>// pages/api/contact.js<br>import nodemailer from &#39;nodemailer&#39;;<br><br>export default function handler(req, res) {<br>  const { name, email, message } = req.body;<br><br>  // Send email using nodemailer<br>  const transporter = nodemailer.createTransport({<br>    service: &#39;gmail&#39;,<br>    auth: {<br>      user: &#39;your_email@gmail.com&#39;,<br>      pass: &#39;your_password&#39;,<br>    },<br>  });<br><br>  const mailOptions = {<br>    from: email,<br>    to: &#39;recipient_email@example.com&#39;,<br>    subject: `New message from ${name}`,<br>    text: message,<br>  };<br><br>  transporter.sendMail(mailOptions, (error, info) =&gt; {<br>    if (error) {<br>      console.log(error);<br>      res.status(500).send(&#39;Error sending message&#39;);<br>    } else {<br>      console.log(`Email sent: ${info.response}`);<br>      res.status(200).send(&#39;Message sent&#39;);<br>    }<br>  });<br>}</pre><p>In this example, we’re using the nodemailer library to send an email with the form data. This serverless function can be triggered by a form submission in your application.</p><p><a href="https://medium.com/@alldevutils/working-with-components-and-layouts-in-next-js-3a13ce51d03b">Working with Components and Layouts in Next.js</a></p><h3>3. Using Next.js with TypeScript</h3><p>TypeScript is a popular language for building scalable and maintainable web applications. Next.js has built-in support for TypeScript, allowing you to write type-safe code and catch errors before runtime.</p><p>To use TypeScript in your Next.js application, you’ll need to add a few dependencies to your project. Here’s an example package.json file that includes the necessary dependencies:</p><pre>{<br>  &quot;name&quot;: &quot;my-next-app&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;next&quot;: &quot;^11.1.2&quot;,<br>    &quot;react&quot;: &quot;^17.0.2&quot;,<br>    &quot;react-dom&quot;: &quot;^17.0.2&quot;,<br>    &quot;typescript&quot;: &quot;^4.3.5&quot;<br>  }<br>}</pre><p>After adding these dependencies, you can create a TypeScript file with the .tsx extension and start writing type-safe code. Here&#39;s an example of a TypeScript component that accepts props:</p><pre>// components/Hello.tsx<br>interface HelloProps {<br>  name: string;<br>}<br><br>export default function Hello({ name }: HelloProps) {<br>  return &lt;h1&gt;Hello, {name}!&lt;/h1&gt;;<br>}</pre><p>In this example, we’re defining an interface for the HelloProps object and using it to type-check the name prop passed to the Hello component.</p><p><a href="https://medium.com/@alldevutils/server-side-rendering-and-data-fetching-3198dc605113">Server-Side Rendering and Data Fetching</a></p><h3>4. Improving Performance in Next.js</h3><p>Performance is a critical factor in any web application, and Next.js provides several features to help you optimize your application’s performance. Let’s look at a few strategies for improving performance in Next.js.</p><h4>a. Code Splitting:</h4><p>Code splitting is a technique that allows you to split your application’s JavaScript code into smaller chunks, which are loaded only when needed. This reduces the initial page load time and improves the overall performance of your application.</p><p>Next.js provides automatic code splitting out of the box. By default, each page of your application is split into its own JavaScript chunk, which is loaded only when the page is requested.</p><p>You can also use dynamic imports to split your code into smaller chunks. For example, you could use dynamic imports to load a component only when it’s needed:</p><pre>import dynamic from &#39;next/dynamic&#39;<br><br>const DynamicComponent = dynamic(() =&gt; import(&#39;../components/DynamicComponent&#39;))<br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to my website!&lt;/h1&gt;<br>      &lt;DynamicComponent /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>In this example, the DynamicComponent is loaded only when it&#39;s needed, reducing the initial page load time.</p><h4>b. Optimizing Images:</h4><p>Images can be a significant source of performance issues, especially on mobile devices. Next.js provides several features to help you optimize images in your application.</p><p>First, Next.js automatically optimizes images that are imported using the next/image component. This component provides several features, including lazy loading and responsive image sizing.</p><p>Here’s an example of how to use the next/image component to display an optimized image:</p><pre>import Image from &#39;next/image&#39;<br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to my website!&lt;/h1&gt;<br>      &lt;Image<br>        src=&quot;/images/my-image.jpg&quot;<br>        alt=&quot;My Image&quot;<br>        width={500}<br>        height={500}<br>      /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>In this example, the Image component automatically optimizes the my-image.jpg file and provides responsive image sizing.</p><p>You can also use the next/image component to lazy load images by setting the loading prop to &quot;lazy&quot;:</p><pre>&lt;Image<br>  src=&quot;/images/my-image.jpg&quot;<br>  alt=&quot;My Image&quot;<br>  width={500}<br>  height={500}<br>  loading=&quot;lazy&quot;<br>/&gt;</pre><h4>c. Caching and Server-side Rendering:</h4><p>Next.js provides several features to help you improve caching and server-side rendering (SSR) performance. Caching refers to the process of storing data in memory or on disk, so it can be retrieved more quickly in the future. SSR refers to the process of rendering your application’s pages on the server, rather than in the client’s browser.</p><p>Next.js supports several caching strategies, including static and incremental caching. Static caching involves caching the entire page, while incremental caching involves caching individual components or sections of a page.</p><p>Next.js also supports server-side rendering, which can improve the initial page load time and improve search engine optimization (SEO). By default, Next.js renders your application’s pages on the server, and provides automatic client-side hydration for interactivity.</p><p>Here’s an example of how to use server-side rendering with Next.js:</p><pre>export async function getServerSideProps() {<br>  const res = await fetch(&#39;https://api.example.com/data&#39;)<br>  const data = await res.json()<br><br>  return {<br>    props: {<br>      data<br>    }<br>  }<br>}<br><br>export default function Home({ data }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to my website!&lt;/h1&gt;<br>      &lt;p&gt;{data}&lt;/p&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>In this example, the getServerSideProps function fetches data from an external API and returns it as a prop to the Home component. The Home component is rendered on the server and then hydrated on the client for interactivity.</p><h4>d. Using Next.js Analytics</h4><p>Next.js provides built-in analytics functionality through the next/script component. This component allows you to add third-party analytics services like Google Analytics, Segment, and Amplitude to your Next.js application.</p><p>To add analytics to your application, you first need to create an account with the analytics service of your choice and obtain a tracking ID or API key. Then, you can add the next/script component to your _document.js file, which is located in the pages folder. Here&#39;s an example of how to add Google Analytics to your application:</p><pre>// _document.js<br><br>import Document, { Html, Head, Main, NextScript } from &#39;next/document&#39;<br><br>class MyDocument extends Document {<br>  render() {<br>    return (<br>      &lt;Html&gt;<br>        &lt;Head&gt;<br>          &lt;script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}&gt;&lt;/script&gt;<br>          &lt;script<br>            dangerouslySetInnerHTML={{<br>              __html: `<br>                window.dataLayer = window.dataLayer || [];<br>                function gtag(){dataLayer.push(arguments);}<br>                gtag(&#39;js&#39;, new Date());<br>                gtag(&#39;config&#39;, &#39;${GA_TRACKING_ID}&#39;, {<br>                  page_path: window.location.pathname,<br>                });<br>              `,<br>            }}<br>          /&gt;<br>        &lt;/Head&gt;<br>        &lt;body&gt;<br>          &lt;Main /&gt;<br>          &lt;NextScript /&gt;<br>        &lt;/body&gt;<br>      &lt;/Html&gt;<br>    )<br>  }<br>}<br><br>export default MyDocument</pre><p>In this example, GA_TRACKING_ID is a variable that contains your Google Analytics tracking ID. The script tags load the Google Analytics library and initialize the tracking code. The dangerouslySetInnerHTML prop sets the configuration options for Google Analytics, including the current page path.</p><p>Once you’ve added the next/script component to your application, you can start tracking user behavior and analyzing your application&#39;s performance.</p><h3>Conclusion</h3><p>In this article, we’ve covered several advanced Next.js concepts, including handling authentication, serverless functions, and using Next.js with TypeScript. We’ve also discussed how to deploy and scale Next.js applications and best practices for development.</p><p>By mastering these concepts, you’ll be able to build powerful, performant web applications with Next.js. Whether you’re building a small blog or a large-scale e-commerce platform, Next.js has the tools and features you need to deliver a seamless user experience.</p><p><a href="https://medium.com/@alldevutils/styling-in-next-js-866ede8d7ab6">Styling in Next.js</a></p><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8439a8752597" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/advanced-next-js-concepts-8439a8752597">Advanced Next.js Concepts</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Styling in Next.js]]></title>
            <link>https://blog.devgenius.io/styling-in-next-js-866ede8d7ab6?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/866ede8d7ab6</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 14:22:42 GMT</pubDate>
            <atom:updated>2023-03-17T20:24:44.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjwgmnEHqoCa7U8SqKiU-A.png" /></figure><p>Styling is a crucial part of web development, and Next.js provides developers with several options to style their applications. In this tutorial, we will explore the various styling options available in Next.js, including CSS Modules, Styled Components, and Responsive Design.</p><p><a href="https://medium.com/@alldevutils/introduction-to-next-js-b3cf00ddd6f1">Introduction to Next.js</a></p><h4><strong>CSS Modules:</strong></h4><p>Next.js supports CSS Modules, which allow developers to write modular CSS code by creating a unique class name for each component. This approach ensures that styles do not clash with other components and makes it easier to maintain code.</p><p>To use CSS Modules, create a CSS file with the .module.css extension, import it into your component, and apply styles using the generated class names. For example, suppose you have a component called Button.js and a CSS module called Button.module.css. In that case, you can import the module and apply styles as follows:</p><pre>import styles from &#39;./Button.module.css&#39;;<br><br>const Button = () =&gt; {<br>  return (<br>    &lt;button className={styles.button}&gt;<br>      Click me<br>    &lt;/button&gt;<br>  )<br>}</pre><h4>Styled Components:</h4><p>Next.js also supports Styled Components, which allow developers to write CSS code as a JavaScript template literal. This approach makes it easier to manage styles and avoids class name collisions. To use Styled Components, install the styled-components library and import it into your component.</p><pre>import styled from &#39;styled-components&#39;;<br><br>const Button = styled.button`<br>  background-color: #f44336;<br>  color: white;<br>  border: none;<br>  padding: 10px 20px;<br>  font-size: 16px;<br>  border-radius: 5px;<br>`;</pre><p>You can then use the Button component in your code and apply styles as follows:</p><pre>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Button&gt;Click me&lt;/Button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Responsive Design:</h4><p>Next.js also supports Responsive Design, which allows your application to adapt to different screen sizes and devices. To implement responsive design, use media queries to define different styles for different screen sizes.</p><p>For example, suppose you want to change the font size of a heading when the screen width is less than 600px. In that case, you can define a media query as follows:</p><pre>@media screen and (max-width: 600px) {<br>  h1 {<br>    font-size: 24px;<br>  }<br>}</pre><h4>Conclusion:</h4><p>In conclusion, Next.js provides developers with several options to style their applications, including CSS Modules, Styled Components, and Responsive Design. Each approach has its benefits and drawbacks, so it’s essential to choose the one that works best for your application’s needs. With this guide, you should now be equipped with the knowledge to implement styling in your Next.js applications.</p><ul><li><a href="https://medium.com/@alldevutils/working-with-components-and-layouts-in-next-js-3a13ce51d03b">Working with Components and Layouts in Next.js</a></li><li><a href="https://medium.com/@alldevutils/server-side-rendering-and-data-fetching-3198dc605113">Server-Side Rendering and Data Fetching</a></li></ul><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><p><a href="https://medium.com/@alldevutils/advanced-next-js-concepts-8439a8752597">Advanced Next.js Concepts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=866ede8d7ab6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/styling-in-next-js-866ede8d7ab6">Styling in Next.js</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Side Rendering and Data Fetching]]></title>
            <link>https://blog.devgenius.io/server-side-rendering-and-data-fetching-3198dc605113?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3198dc605113</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 14:04:35 GMT</pubDate>
            <atom:updated>2023-03-17T20:24:37.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjwgmnEHqoCa7U8SqKiU-A.png" /></figure><p>Server-side rendering (SSR) is a key feature of Next.js that allows us to render our pages on the server, rather than in the browser. This has many benefits, including improved performance, better search engine optimization (SEO), and improved user experience.</p><p>In this article, we will explore how to use SSR and data fetching in Next.js, including how to use the getStaticProps and getServerSideProps functions.</p><p><a href="https://medium.com/@alldevutils/introduction-to-next-js-b3cf00ddd6f1">Introduction to Next.js</a></p><h3><strong>What is Server-Side Rendering?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xK7KpQVO2kxjfaAIiQe2LA.png" /></figure><p>Traditionally, web applications have been built using client-side rendering (CSR), which means that the HTML, CSS, and JavaScript are all loaded in the browser. This approach can be slow and inefficient, especially for large applications or pages with a lot of content.</p><p>SSR, on the other hand, involves rendering the HTML on the server and sending it to the browser as a fully formed page. This approach can be faster and more efficient, especially for pages with a lot of content or dynamic data.</p><h3>Using Server-Side Rendering in Next.js</h3><p>Next.js makes it easy to use SSR in our applications. By default, Next.js uses a hybrid approach that combines SSR and CSR, which provides the best of both worlds.</p><p>To use SSR in Next.js, we can use the getStaticProps and getServerSideProps functions. These functions allow us to fetch data on the server and pass it to our components as props.</p><h4>Using getStaticProps</h4><p>The getStaticProps function is used for pre-rendering static pages. This means that the data is fetched at build time and the HTML is generated in advance. This can improve performance and reduce the load on our servers.</p><p>To use getStaticProps, we need to create a page component and export the getStaticProps function. Here’s an example:</p><pre>import { getStaticProps } from &#39;next&#39;;<br><br>export default function Home({ data }) {<br>  return &lt;div&gt;{data}&lt;/div&gt;;<br>}<br><br>export async function getStaticProps() {<br>  // Fetch data from an API<br>  const res = await fetch(&#39;https://api.example.com/data&#39;);<br>  const data = await res.json();<br><br>  // Return the data as props<br>  return {<br>    props: {<br>      data<br>    }<br>  };<br>}</pre><p>In this example, we have created a Home component that receives the data as a prop. We have also exported the getStaticProps function, which fetches the data from an API and returns it as props.</p><h4><strong>Using getServerSideProps</strong></h4><p>The getServerSideProps function is used for pre-rendering dynamic pages. This means that the data is fetched on each request and the HTML is generated on the server. This can be slower than using getStaticProps, but it allows us to fetch data that changes frequently.</p><p>To use getServerSideProps, we need to create a page component and export the getServerSideProps function. Here’s an example:</p><pre>import { getServerSideProps } from &#39;next&#39;;<br><br>export default function Home({ data }) {<br>  return &lt;div&gt;{data}&lt;/div&gt;;<br>}<br><br>export async function getServerSideProps() {<br>  const res = await fetch(&#39;https://api.example.com/data&#39;);<br>  const data = await res.json();<br><br>  return {<br>    props: {<br>      data,<br>    },<br>  };<br>}</pre><p>In this example, we have created a Home component that receives the data as a prop. We have also exported the getServerSideProps function, which fetches the data from an API on each request and returns it as props.</p><p><a href="https://medium.com/@alldevutils/working-with-components-and-layouts-in-next-js-3a13ce51d03b">Working with Components and Layouts in Next.js</a></p><h4><strong>Conclusion</strong></h4><p>In this article, we have explored how to use server-side rendering and data fetching in Next.js. We have learned how to use the getStaticProps and getServerSideProps functions to fetch data on the server and pass it to our components as props.</p><p>By using these techniques, we can improve the performance and user experience of our Next.js applications, as well as improve SEO and reduce the load on our website.</p><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><p><a href="https://medium.com/@alldevutils/styling-in-next-js-866ede8d7ab6">Styling in Next.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3198dc605113" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/server-side-rendering-and-data-fetching-3198dc605113">Server-Side Rendering and Data Fetching</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Components and Layouts in Next.js]]></title>
            <link>https://javascript.plainenglish.io/working-with-components-and-layouts-in-next-js-3a13ce51d03b?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a13ce51d03b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 13:38:18 GMT</pubDate>
            <atom:updated>2024-07-18T11:10:54.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjwgmnEHqoCa7U8SqKiU-A.png" /><figcaption>Next.Js Series of Lectures from Beginners to Advanced Level</figcaption></figure><p>In this article, we will be exploring how to work with components and layouts in Next.js. Components are the building blocks of any React-based application, and Next.js provides a powerful way to work with them. Layouts, on the other hand, help us create a consistent design across our application. We will cover how to create reusable components, implement layouts, and use the Head component in Next.js.</p><h3>Creating Reusable Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDOpxIungBhsdgyN_uEPeA.png" /><figcaption>Component Tree in Next.js</figcaption></figure><p>One of the key benefits of React is the ability to create reusable components. This applies to Next.js as well. We can create a component once and reuse it across multiple pages of our application. This not only saves time but also ensures consistency across the application.</p><blockquote><em>💡 </em>Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong><em>DifferAI</em></strong></a>.</blockquote><blockquote>Available for <strong><em>free</em> </strong>exclusively on the <strong><em>free and open blogging platform, </em></strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong>.</strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><p>To create a reusable component in Next.js, we first need to create a file with a .js extension in the components directory of our project. For example, let’s say we want to create a component for a header. We can create a file named Header.js in the components directory.</p><p>Here’s an example of what our Header.js file could look like:</p><pre>import React from &#39;react&#39;;<br><br>const Header = () =&gt; {<br>  return (<br>    &lt;header&gt;<br>      &lt;h1&gt;My Application&lt;/h1&gt;<br>      &lt;nav&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;&lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>          &lt;li&gt;&lt;a href=&quot;/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>          &lt;li&gt;&lt;a href=&quot;/contact&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/nav&gt;<br>    &lt;/header&gt;<br>  );<br>};<br><br>export default Header;</pre><p>In this example, we have created a simple header component that includes a navigation menu with links to the home, about, and contact pages.</p><p>Now that we have created the Header component, we can use it across our application. For example, let’s say we want to use the Header component on our home page. We can import the Header component in our index.js file and use it like this:</p><pre>import Header from &#39;../components/Header&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      &lt;h1&gt;Welcome to my application!&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;</pre><p>In this example, we have imported the Header component and used it on our home page. We have also included a welcome message below the header.</p><p><a href="https://medium.com/@alldevutils/introduction-to-next-js-b3cf00ddd6f1">Introduction to Next.js</a></p><h3>Implementing Layouts</h3><figure><img alt="Images explaining Layout and components in one simple figure." src="https://cdn-images-1.medium.com/max/495/1*B6yYjfPjLgLWh9h0DHj2tA.jpeg" /><figcaption>Layout is like a single wrapper for multiple components and pages.</figcaption></figure><p>In addition to creating reusable components, Next.js also allows us to create layouts. Layouts are used to create a consistent design across our application. We can use layouts to include common elements such as a header, footer, and navigation menu on every page of our application.</p><p>To create a layout in Next.js, we first need to create a file with a .js extension in the layouts directory of our project. For example, let’s say we want to create a layout that includes a header, footer, and navigation menu. We can create a file named DefaultLayout.js in the layouts directory.</p><p>Here’s an example of what our DefaultLayout.js file could look like:</p><pre>import Header from &#39;../components/Header&#39;;<br><br>const DefaultLayout = ({ children }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      {children}<br>      &lt;footer&gt;<br>        &lt;p&gt;&amp;copy; 2022 My Application&lt;/p&gt;<br>      &lt;/footer&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default DefaultLayout;</pre><p>In this example, we have created a layout component that includes the Header component, the content of the page, and a footer.</p><p>Now that we have created the DefaultLayout component, we can use it across our application. For example, let’s say we want to use the DefaultLayout component on our home page. We can import the DefaultLayout component in our index.js file and use it like this:</p><pre>import DefaultLayout from &#39;../layouts/DefaultLayout&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;DefaultLayout&gt;<br>      &lt;h1&gt;Welcome to my application!&lt;/h1&gt;<br>    &lt;/DefaultLayout&gt;<br>  );<br>};<br><br>export default Home;</pre><p>In this example, we have imported the DefaultLayout component and used it on our home page. We have also included a welcome message within the DefaultLayout component.</p><p><strong>Using the Head Component</strong></p><p>The Head component is a powerful tool that allows us to add metadata to our pages. This metadata can include the page title, meta tags, and links to stylesheets and scripts.</p><p>To use the Head component in Next.js, we need to import it from the next/head module. We can then use it within our pages to add metadata. For example, let’s say we want to set the title of our home page. We can use the Head component like this:</p><pre>import Head from &#39;next/head&#39;;<br>import DefaultLayout from &#39;../layouts/DefaultLayout&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;DefaultLayout&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;My Application - Home&lt;/title&gt;<br>      &lt;/Head&gt;<br>      &lt;h1&gt;Welcome to my application!&lt;/h1&gt;<br>    &lt;/DefaultLayout&gt;<br>  );<br>};<br><br>export default Home;</pre><p>In this example, we have imported the Head component from the next/head module and used it within our Home component to set the title of the page to “My Application — Home”.</p><p><strong>Conclusion</strong></p><p>In this article, we have explored how to work with components and layouts in Next.js. We have learned how to create reusable components, implement layouts, and use the Head component to add metadata to our pages. By using these techniques, we can create a consistent design across our application and save time by reusing components.</p><p>Thank you for reading! I hope this article has been helpful in your journey to learn Next.js.</p><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><p><a href="https://medium.com/@alldevutils/server-side-rendering-and-data-fetching-3198dc605113">Server-Side Rendering and Data Fetching</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a13ce51d03b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/working-with-components-and-layouts-in-next-js-3a13ce51d03b">Working with Components and Layouts in Next.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Next.js]]></title>
            <link>https://blog.devgenius.io/introduction-to-next-js-b3cf00ddd6f1?source=rss-618119d9248c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3cf00ddd6f1</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[AllDevUtils]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 18:19:52 GMT</pubDate>
            <atom:updated>2023-03-17T06:05:07.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjwgmnEHqoCa7U8SqKiU-A.png" /><figcaption>One of the most loved react.js frameworks</figcaption></figure><p>Are you looking to build web applications with React but are not sure where to start? Look no further than Next.js, a powerful framework that allows you to easily build server rendered React applications.</p><p>Hi, I’m Bhupendra. I will derive you through Next.js (my favorite react.js framework). So, first things first. In this tutorial, we’ll go over the basics of Next.js and show you how to get started with your first project.</p><p>I’m going to divide this article as:</p><ul><li><strong>What is Next.js and why should you use it?</strong></li><li><strong>Setting up your first Next.js project</strong></li><li><strong>Creating and navigating pages in Next.js</strong></li></ul><h3>What is Next.js and why should you use it?</h3><p>Next.js is a React-based framework that allows you to build server-side rendered applications with ease. With Next.js, you can create dynamic and fast-loading web pages that are optimized for search engines and social media platforms. Some of the key benefits of using Next.js include:</p><ul><li><strong><em>Automatic code splitting</em></strong> for faster page loads.</li><li><strong><em>Server-side rendering</em></strong> for improved SEO and performance.</li><li>Built-in support for CSS modules and styled components.</li><li><strong><em>Easy deployment</em></strong> with Vercel, the platform that was built specifically for Next.js</li></ul><h3>Setting up your first Next.js project</h3><p>To get started with Next.js, you’ll need to have Node.js and npm (Node Package Manager) installed on your machine.</p><p>Once you have these pre-requisites installed, you can create a new Next.js project by running the following commands:</p><pre>npx create-next-app my-app<br>cd my-app<br>npm run dev</pre><p>This will create a new Next.js project in a directory called my-app and start a development server at <a href="http://localhost:3000.">http://localhost:3000.</a></p><h3>Creating and navigating pages in Next.js</h3><p>Next.js uses a file-based routing system, which means that you can create a new page simply by creating a new file in the pages directory.</p><p>For example, if you want to create a new page at /about, you can create a file called about.js in the pages directory with the following content:</p><pre>function About() {<br>  return &lt;h1&gt;About Page&lt;/h1&gt;<br>}<br><br>export default About</pre><p>Once you create the about.js file, you can navigate to the page at <a href="http://localhost:3000/about.">http://localhost:3000/about.</a></p><p>In conclusion, Next.js is a <strong>powerful framework</strong> that makes it easy to build server-side rendered React applications. In this tutorial, we covered the basics of Next.js and showed you how to set up your first project and create new pages. In the next tutorial, we’ll cover some intermediate Next.js concepts such as server-side rendering and using Next.js API routes.</p><blockquote>If you enjoyed reading this article, please follow <a href="https://medium.com/@alldevutils"><strong>AllDevUtils</strong></a> for more amazing content like this!</blockquote><ul><li><a href="https://medium.com/@alldevutils/working-with-components-and-layouts-in-next-js-3a13ce51d03b">Working with Components and Layouts in Next.js</a></li><li><a href="https://medium.com/@alldevutils/server-side-rendering-and-data-fetching-3198dc605113">Server-Side Rendering and Data Fetching</a></li><li><a href="https://medium.com/@alldevutils/styling-in-next-js-866ede8d7ab6">Styling in Next.js</a></li><li><a href="https://medium.com/@alldevutils/advanced-next-js-concepts-8439a8752597">Advanced Next.js Concepts</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3cf00ddd6f1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/introduction-to-next-js-b3cf00ddd6f1">Introduction to Next.js</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>