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:
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
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:
- 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"], }, };
- 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*"], };
- postArticle.tsx: function responsible for submitting the article data to our server.
.env.local NEXTAUTH_SECRET = SubsTituaPorToken
- 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() <ol> <li> deleteArticle.tsx: function responsible for removing a specific article from our database. </li> </ol> <pre class="brush:php;toolbar:false">'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 ", }; export default async function RootLayout({ children, }: { children: React.ReactNode; }) { const session = await getServerSession(authOptions); return ( <provider session="{session}"> {children} </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:
- getArticles.ts - returns all the articles that will be displayed in the component.
- 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:
- Write an article in Markdown format.
- Assign an image to the article.
- Preview the Markdown text before submitting it to the server.
The page uses several hooks:
- useCallback - used to memoize functions.
- useState - allows you to add a state variable to our component.
- useSession - lets us check if the user is authenticated and obtain the authentication token.
For this, we will use two components:
- TextEditor.tsx: the text editor we wrote previously.
- Preview.tsx: a component for displaying files in Markdown format.
While constructing this page, we will make use of our API:
- 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)} /> </preview> </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></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"></aioutlinesend> </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"></aioutlinefolderopen> 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></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)} /> </preview> </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></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"></aioutlineedit> </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"></aioutlinefolderopen> 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> </div> </div> </div> </form> </div></section></htmlinputelement></htmlinputelement></string></string></boolean></string></object></iarticle>
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)