Home >Web Front-end >JS Tutorial >Building a Dynamic Blog Dashboard with Next.js

Building a Dynamic Blog Dashboard with Next.js

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 17:04:10635browse

Introduction

Hello, how are you? This is Vítor, coming back with a new project to help you enhance your programming skills. It’s been a while since I last published a tutorial. Over the past few months, I took some time to rest and focus on other activities. During this period, I developed a small web project: a blog, which became the focus of this tutorial.

In this guide, we will create the frontend of a blog page capable of rendering Markdown. The application will include public and private routes, user authentication, and the ability to write Markdown text, add photos, display articles, and much more.

Feel free to customize your application however you prefer—I even encourage it.

You can access the repository for this application here:

Building a Dynamic Blog Dashboard with Next.js Gondrak08 / blog-platform

A blog plataform made with Next.js/typescript.

Plataforma para blog

  • Tutorial em texto

Ingredientes

  • next-auth - biblioteca de autenticação para Next.js
  • github.com/markdown-it/markdown-it - markdown biblioteca.
  • github.com/sindresorhus/github-markdown-css- Para dar estilo ao nosso editor markdown.
  • github.com/remarkjs/react-markdown - Biblioteca para renderizar markdown em nosso componente react.
  • github.com/remarkjs/remark-react/tree/4722bdf - Plugin para transformar Markdown em React.
  • codemirror.net - Editor componente para web.
  • react-icons - lib de icones para react.

Como usar

npm i
npm run start

Server

você pode encontrar o servidor dessa aplicação em server


View on GitHub


This tutorial also includes the writing of the Node.js server that will be used in this guide:

I hope you enjoy it.

Happy coding!

Libraries

Here is a summary of the libraries used in this project:

  • next-auth - Authentication library for Next.js
  • github.com/markdown-it/markdown-it - Markdown library.
  • github.com/sindresorhus/github-markdown-css - For styling our Markdown editor.
  • github.com/remarkjs/react-markdown - Library for rendering Markdown in our React component.
  • github.com/remarkjs/remark-react/tree/4722bdf - Plugin to transform Markdown into React.
  • codemirror.net - Web component editor.
  • react-icons - Icon library for React.

Creating the React Project

We will use the latest version of the Next.js framework, which, at the time of writing this tutorial, is version 13.4.

Run the following command to create the project:

npm i
npm run start

During the installation, select the template settings. In this tutorial, I will use TypeScript as the programming language and the Tailwind CSS framework for styling our application.

Configuration

Now let's install all the libraries we will use.

Markdown
npx create-next-app myblog
React Remark
npm i  markdown-it @types/markdown-it markdown-it-style github-markdown-css react-markdown
Codemirror
remark remark-gfm remark-react
Icons
npm @codemirror/commands @codemirror/highlight @codemirror/lang-javascript @codemirror/lang-markdown @codemirror/language @codemirror/language-data @codemirror/state @codemirror/theme-one-dark @codemirror/view

Then clean up the initial structure of your installation by removing everything we won’t be using.

Architecture

This is the final structure of our application.

npm i react-icons @types/react-icons

First Steps

Configuring next.config

In the root of the project, in the file next.config.js, let's configure the domain address from which we will access the images for our articles. For this tutorial, or if you're using a local server, we will use localhost.

Make sure to include this configuration to ensure the correct loading of images in your application.

src-
  |- app/
  |    |-(pages)/
  |    |      |- (private)/
  |    |      |       |- (home)
  |    |      |       |- editArticle/[id]
  |    |      |       |
  |    |      |       |- newArticle
  |    |      | - (public)/
  |    |              | - article/[id]
  |    |              | - login
  |    |
  |   api/
  |    |- auth/[...nextAuth]/route.ts
  |    |- global.css
  |    |- layout.tsx
  |
  | - components/
  | - context/
  | - interfaces/
  | - lib/
  | - services/
middleware.ts

Configuring Middleware

In the root folder of the application src/, create a middleware.ts to verify access to private routes.

const nextConfig = {
   images: {
    domains: ["localhost"],
  },
};

To learn more about middlewares and everything you can do with them, check the documentation.

Configuring Authentication Route

Inside the /app folder, create a file named route.ts in api/auth/[...nextauth]. It will contain the configuration for our routes, connecting to our authentication API using the CredentialsProvider.

The CredentialsProvider allows you to handle login with arbitrary credentials, such as username and password, domain, two-factor authentication, hardware device, etc.

First, in the root of your project, create a .env.local file and add a token that will be used as our secret.

npm i
npm run start

Next, let's write our authentication system, where this NEXTAUTH_SECRET will be added to our secret in the src/app/auth/[...nextauth]/routes.ts file.

npx create-next-app myblog

Authentication Provider

Let's create an authentication provider, a context, that will share our user's data across the pages of our private route. We will later use it to wrap one of our layout.tsx files.

Create a file in src/context/auth-provider.tsx with the following content:

npm i  markdown-it @types/markdown-it markdown-it-style github-markdown-css react-markdown

Global Styles

Overall, in our application, we will use Tailwind CSS to create our styling. However, in some places, we will share custom CSS classes between pages and components.

remark remark-gfm remark-react

Layouts

Now let's write the layouts, both private and public.

app/layout.tsx

npm @codemirror/commands @codemirror/highlight @codemirror/lang-javascript @codemirror/lang-markdown @codemirror/language @codemirror/language-data @codemirror/state @codemirror/theme-one-dark @codemirror/view

pages/layout.tsx

npm i react-icons @types/react-icons

API Calls

Our application will make several calls to our API, and you can adapt this application to use any external API. In our example, we are using our local application. If you haven’t seen the backend tutorial and the server creation, check it out.

In src/services/, let's write the following functions:

  1. authService.ts: function responsible for authenticating our user on the server.
src-
  |- app/
  |    |-(pages)/
  |    |      |- (private)/
  |    |      |       |- (home)
  |    |      |       |- editArticle/[id]
  |    |      |       |
  |    |      |       |- newArticle
  |    |      | - (public)/
  |    |              | - article/[id]
  |    |              | - login
  |    |
  |   api/
  |    |- auth/[...nextAuth]/route.ts
  |    |- global.css
  |    |- layout.tsx
  |
  | - components/
  | - context/
  | - interfaces/
  | - lib/
  | - services/
middleware.ts

2.refreshAccessToken.tsx:

const nextConfig = {
   images: {
    domains: ["localhost"],
  },
};
  1. getArticles.tsx: function responsible for fetching all the articles saved in our database:
export { default } from "next-auth/middleware";
export const config = {
  matcher: ["/", "/newArticle/", "/article/", "/article/:path*"],
};
  1. postArticle.tsx: function responsible for submitting the article data to our server.
.env.local
NEXTAUTH_SECRET = SubsTituaPorToken
  1. editArticle.tsx: function responsible for modifying a specific article within the database.
import NextAuth from "next-auth/next";
import type { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { authenticate } from "@/services/authService";
import refreshAccessToken from "@/services/refreshAccessToken";

export const authOptions: AuthOptions = {
  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: {
          name: "email",
          label: "email",
          type: "email",
          placeholder: "Email",
        },
        password: {
          name: "password",
          label: "password",
          type: "password",
          placeholder: "Password",
        },
      },
      async authorize(credentials, req) {
        if (typeof credentials !== "undefined") {
          const res = await authenticate({
            email: credentials.email,
            password: credentials.password,
          });
          if (typeof res !== "undefined") {
            return { ...res };
          } else {
            return null;
          }
        } else {
          return null;
        }
      },
    }),
  ],

  session: { strategy: "jwt" },
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async jwt({ token, user, account }: any) {
      if (user && account) {
        return {
          token: user?.token,
          accessTokenExpires: Date.now() + parseInt(user?.expiresIn, 10),
          refreshToken: user?.tokenRefresh,
        };
      }

      if (Date.now() < token.accessTokenExpires) {
        return token;
      } else {
        const refreshedToken = await refreshAccessToken(token.refreshToken);
        return {
          ...token,
          token: refreshedToken.token,
          refreshToken: refreshedToken.tokenRefresh,
          accessTokenExpires:
            Date.now() + parseInt(refreshedToken.expiresIn, 10),
        };
      }
    },
    async session({ session, token }) {
      session.user = token;
      return session;
    },
  },

  pages: {
    signIn: "/login",
    signOut: "/login",
  },
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
  1. deleteArticle.tsx: function responsible for removing a specific article from our database.
'use client';
import React from 'react';
import { SessionProvider } from "next-auth/react";
export default function Provider({
    children,
    session
}: {
    children: React.ReactNode,
    session: any
}): React.ReactNode {
    return (
        <SessionProvider session={session} >
            {children}
        </SessionProvider>
    )
};

Components

Next, let's write each component used throughout the application.

Components/Navbar.tsx

A simple component with two navigation links.

/*global.css*/
.container {
  max-width: 1100px;
  width: 100%;
  margin: 0px auto;
}

.image-container {
  position: relative;
  width: 100%;
  height: 5em;
  padding-top: 56.25%; /* Aspect ratio 16:9 (dividindo a altura pela largura) */
}

.image-container img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

@keyframes spinner {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 10px solid #f3f3f3;
  border-top: 10px solid #293d71;
  border-radius: 50%;
  animation: spinner 1.5s linear infinite;
}

Components/Loading.tsx

A simple loading component, used while waiting for API calls to complete.

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Provider from "@/context/auth-provider";
import { getServerSession } from "next-auth";
import { authOptions } from "./api/auth/[...nextauth]/route";
const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Markdown Text Editor",
  description: "Created by <@vitorAlecrim>",
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getServerSession(authOptions);
  return (
    <Provider session={session}>
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
    </Provider>
  );
}

Components/Pagination.tsx

A pagination component used on our page displaying all of our articles, in our private route. You can find a more detailed article on how to write this component here

npm i
npm run start

Components/ArticleCard.tsx

A card component for displaying written articles.

This component also contains a link that will lead to both the article display page and the page for editing a previously written article.

npx create-next-app myblog

Components/ArticleList.tsx

A component responsible for making API calls and displaying the response.

Here, we will use two API calls through the functions we wrote:

  1. getArticles.ts - returns all the articles that will be displayed in the component.
  2. removeArticle - removes a specific article from our list and from our server.

We will use the Pagination.tsx component, previously written, to split the number of articles across pages.

npm i  markdown-it @types/markdown-it markdown-it-style github-markdown-css react-markdown

Pages

Next, we will go through each of our pages, divided by their respective routes.

Public Pages

Login

This is the homepage of our application. It is a simple page, and you can modify it as you see fit. On this page, we will use the signin function provided by the next-auth navigation library.

In the file src/app/pages/public/login/page.tsx.

remark remark-gfm remark-react

Article Page

To create the article reading page, we will develop a dynamic page.

Every blog platform you've visited likely has a dedicated page for reading articles, accessible via URL. The reason for this is a dynamic page route. Fortunately, Next.js makes this easy with its new AppRouter method, making our lives much simpler.

First: we need to create the route in our structure by adding a [id] folder. This will result in the following structure: pages/(public)/articles/[id]/pages.tsx.

  • The id corresponds to the slug of our navigation route.
  • params is a property passed through the tree of our application containing the navigation slug.
npm @codemirror/commands @codemirror/highlight @codemirror/lang-javascript @codemirror/lang-markdown @codemirror/language @codemirror/language-data @codemirror/state @codemirror/theme-one-dark @codemirror/view

Second: use the MarkdownIt library to enable the page to display text in Markdown format.

npm i react-icons @types/react-icons

And finally,

once the page is ready, by accessing, for example, localhost:3000/articles/1 in the browser, you will be able to view the article with the provided ID.

In our case, the ID will be passed through navigation when clicking on one of the ArticleCards.tsx components, which will be rendered on the main page of our private route.

src-
  |- app/
  |    |-(pages)/
  |    |      |- (private)/
  |    |      |       |- (home)
  |    |      |       |- editArticle/[id]
  |    |      |       |
  |    |      |       |- newArticle
  |    |      | - (public)/
  |    |              | - article/[id]
  |    |              | - login
  |    |
  |   api/
  |    |- auth/[...nextAuth]/route.ts
  |    |- global.css
  |    |- layout.tsx
  |
  | - components/
  | - context/
  | - interfaces/
  | - lib/
  | - services/
middleware.ts

Private Pages

Here are our private pages, which can only be accessed once the user is authenticated in our application.

Home

Inside our app/pages/ folder, when a file is declared inside (), it means that route corresponds to /.

In our case, the (Home) folder refers to the homepage of our private route. It is the first page the user sees upon authenticating into the system. This page will display the list of articles from our database.

The data will be processed by our ArticlesList.tsx component. If you haven’t written this code yet, refer back to the components section.

In app/(pages)/(private)/(home)/page.tsx.

npm i
npm run start

New Article

This is one of the most important pages of our application, as it allows us to register our articles.

This page will enable the user to:

  1. Write an article in Markdown format.
  2. Assign an image to the article.
  3. Preview the Markdown text before submitting it to the server.

The page uses several hooks:

  1. useCallback - used to memoize functions.
  2. useState - allows you to add a state variable to our component.
  3. useSession - lets us check if the user is authenticated and obtain the authentication token.

For this, we will use two components:

  1. TextEditor.tsx: the text editor we wrote previously.
  2. Preview.tsx: a component for displaying files in Markdown format.

While constructing this page, we will make use of our API:

  1. POST: Using our function postArticle, we will send the article to the server.

We will also use the useSession hook, provided by the next-auth library, to obtain the user's authentication token, which will be used to register the article on the server.

This will involve three distinct API calls.
In app/pages/(private)/newArticle/page.tsx.

"use client";
import React, { ChangeEvent, useCallback, useState } from "react";
import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";
import postArtical from "@/services/postArticle";
import { AiOutlineFolderOpen } from "react-icons/ai";
import { RiImageEditLine } from "react-icons/ri";

import Image from "next/image";
import TextEditor from "@/components/textEditor";
import Preview from "@/components/PreviewText";
import { AiOutlineSend } from "react-icons/ai";
import { BsBodyText } from "react-icons/bs";

export default function NewArticle(params:any) {
  const { data: session }: any = useSession({
    required: true,
    onUnauthenticated() {
      redirect("/login");
    },
  });
  const [imageUrl, setImageUrl] = useState<object>({});
  const [previewImage, setPreviewImage] = useState<string>("");
  const [previewText, setPreviewText] = useState<boolean>(false);
  const [title, setTitle] = useState<string>("");
  const [doc, setDoc] = useState<string>("# Escreva o seu texto... n");
  const handleDocChange = useCallback((newDoc: any) => {
    setDoc(newDoc);
  }, []);

  if (!session?.user) return null;

  const handleArticleSubmit = async (e:any) => {
        e.preventDefault();
    const token: string = session.user.token;
    try {
      const res = await postArtical({
        id: session.user.userId.toString(),
        token: token,
        imageUrl: imageUrl,
        title: "title,"
        doc: doc,
      });
      console.log('re--->', res);
      redirect('/success');
    } catch (error) {
      console.error('Error submitting article:', error);
      // Handle error if needed
      throw error;
    }
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const url = URL.createObjectURL(file);
      setPreviewImage(url);
      setImageUrl(file);
    }
  };

  const handleTextPreview = (e: any) => {
    e.preventDefault();
    setPreviewText(!previewText);
  };
  return (
    <section className="w-full h-full min-h-screen relative py-8">
      {previewText && (
        <div className="absolute right-16 top-5 p-5 border-2 border-slate-500 bg-slate-100 rounded-xl w-full max-w-[33em] z-30">
          <Preview
            doc={doc}
            title={title}
            previewImage={previewImage}
            onPreview={() => setPreviewText(!previewText)}
          />
        </div>
      )}

      <form className="relative mx-auto max-w-[700px] h-full min-h-[90%] w-full p-2 border-2 border-slate-200 rounded-md  bg-slate-50 drop-shadow-xl flex flex-col gap-2 ">
        {" "}
        <div className="flex justify-between items-center">
          <button
            className="border-b-2 rounded-md border-slate-500 p-2 flex items-center gap-2  hover:border-slate-400 hover:text-slate-800"
            onClick={handleTextPreview}
          >
            <BsBodyText />
            Preview
          </button>{" "}
          <button
            className="group border border-b-2 border-slate-500 rounded-md p-2 flex items-center gap-2 hover:border-slate-400 hover:text-slate-800 "
            onClick={handleArticleSubmit}
          >
            Enviar Texto
            <AiOutlineSend className="w-5 h-5 group-hover:text-red-500" />
          </button>
        </div>
        <div className="header-wrapper flex flex-col gap-2 ">
          <div className="image-box">
            {previewImage.length === 0 && (
              <div className="select-image">
                <label
                  htmlFor="image"
                  className="p-4 border-dashed border-4 border-slate-400 cursor-pointer flex flex-col items-center justify-center"
                >
                  <AiOutlineFolderOpen className="w-7 h-7" />
                  drang and drop image
                </label>
                <input
                 >



<h4>
  
  
  Edit Article
</h4>

<p>A page similar to <em>New Article</em> (newArticle), with some differences.</p>

<p>First, we define a dynamic route where we receive an id as a navigation parameter. This is very similar to what was done on the article reading page. <br>
app/(pages)/(private)/editArticle/[id]/page.tsx<br>
</p><pre class="brush:php;toolbar:false">"use client";
import React, { useState, useEffect, useCallback, useRef, ChangeEvent } from "react";
import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";
import Image from 'next/image';

import { IArticle } from "@/interfaces/article.interface";
import { AiOutlineEdit } from "react-icons/ai";
import { BsBodyText } from "react-icons/bs";
import { AiOutlineFolderOpen } from "react-icons/ai";
import { RiImageEditLine } from "react-icons/ri";

import Preview from "@/components/PreviewText";
import TextEditor from "@/components/textEditor";
import Loading from '@/components/Loading';
import editArtical from "@/services/editArticle";

export default function EditArticle({ params }: { params: any }) {
 const { data: session }: any = useSession({
    required: true,
    onUnauthenticated() {
      redirect("/login");
    },
  });
  const id: number = params.id;
  const [article, setArticle] = useState<IArticle | null>(null);
  const [imageUrl, setImageUrl] = useState<object>({});
  const [previewImage, setPreviewImage] = useState<string>("");
  const [previewText, setPreviewText] = useState<boolean>(false)
  const [title, setTitle] = useState<string>("");
  const [doc, setDoc] = useState<string>('');
  const handleDocChange = useCallback((newDoc: any) => {
    setDoc(newDoc);
  }, []);
  const inputRef= useRef<HTMLInputElement>(null);

  const fetchArticle = async (id: number) => {
    try {
      const response = await fetch(
        `http://localhost:8080/articles/getById/${id}`,
      );
      const jsonData = await response.json();
      setArticle(jsonData);
    } catch (err) {
      console.log("something went wrong:", err);
    }
  };
  useEffect(() => {
    if (article !== null || article !== undefined) {
      fetchArticle(id);
    }
  }, [id]);

  useEffect(()=>{
    if(article != null && article.content){
        setDoc(article.content)
    }

    if(article !=null && article.image){
      setPreviewImage(`http://localhost:8080/`   article.image)
    }
  },[article])

  const handleArticleSubmit = async (e:any) => {
     e.preventDefault();
    const token: string = session.user.token;
    try{
      const res = await editArtical({
      id: id,
      token: token,
      imageUrl:imageUrl,
      title: title,
      doc: doc,
      });
        console.log('re--->',res)
        return res;
    } catch(error){
    console.log("Error:", error)
    }
  };
  const handleImageClick = ()=>{
      console.log('hiii')
    if(inputRef.current){
      inputRef.current.click();
    }
  }const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const url = URL.createObjectURL(file);
      setPreviewImage(url);
      setImageUrl(file);
    }

  };
   const handleTextPreview = (e: any) => {
    e.preventDefault();
    setPreviewText(!previewText);
    console.log('hello from preview!')
  };

  if(!article) return <Loading/>
  if(article?.content)
  return (
    <section className='w-full h-full min-h-screen relative py-8'>
      {previewText && (
        <div className="absolute right-16 top-5 p-5 border-2 border-slate-500 bg-slate-100 rounded-xl w-full max-w-[33em] z-30">
          <Preview
            doc={doc}
            title={title}
            previewImage={previewImage}
            onPreview={() => setPreviewText(!previewText)}
          />
        </div>
      )}

      <div className='relative mx-auto max-w-[700px] h-full min-h-[90%] w-full p-2 border-2 border-slate-200 rounded-md  bg-white drop-shadow-md flex flex-col gap-2'>
        <form className='relative mx-auto max-w-[700px] h-full min-h-[90%] w-full p-2 border-2 border-slate-200 rounded-md  bg-slate-50 drop-shadow-md flex flex-col gap-2 '>
          {" "}
          <div className='flex justify-between items-center'>
            <button
              className='border-b-2 rounded-md border-slate-500 p-2 flex items-center gap-2  hover:border-slate-400 hover:text-slate-800'
              onClick={handleTextPreview}
            >
              <BsBodyText />
              Preview
            </button>{" "}
            <button
              className='group border border-b-2 border-slate-500 rounded-md p-2 flex items-center gap-2 hover:border-slate-400 hover:text-slate-800 '
              onClick={handleArticleSubmit}
            >
                Edite artigo 
              <AiOutlineEdit className='w-5 h-5 group-hover:text-red-500' />
            </button>
          </div>
          <div className='header-wrapper flex flex-col gap-2 '>
            <div className='image-box'>
              {previewImage.length === 0 && (
                <div className='select-image'>
                  <label
                    htmlFor='image'
                    className='p-4 border-dashed border-4 border-slate-400 cursor-pointer flex flex-col items-center justify-center'
                  >
                    <AiOutlineFolderOpen className='w-7 h-7' />
                    drang and drop image
                  </label>
                  <input
                   >



<h2>
  
  
  Conclusion
</h2>

<p>First, I would like to thank you for taking the time to read this tutorial, and I also want to congratulate you on completing it. I hope it served you well and that the step-by-step instructions were easy to follow.</p>

<p>Second, I’d like to highlight a few points about what we just built. This is the foundation of a blog system, and there’s still much to add, such as a public page displaying all articles, a user registration page, or even a custom 404 error page. If, during the tutorial, you wondered about these pages and missed them, know that this was intentional. This tutorial provided you with enough experience to create these new pages on your own, add many others, and implement new features.</p>

<p>Thank you very much, and until next time. o/</p>


          

            
        

The above is the detailed content of Building a Dynamic Blog Dashboard with Next.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn