Unverified Commit 5142c0e5 authored by Adem ilter's avatar Adem ilter Committed by GitHub

Example blog with comments (#24829)

* initial commit

* delete comment

* env name fix

* Update README.md

* remove hapi-boom

* use next-image

* fix alt attr

* date fix for blog posts

* reset gitignore

* fix react best-practices

* prettier

* mdx to md

* fix prettier config. lint 👍

* Update examples/blog-with-comment/components/comment/list.js
Co-authored-by: 's avatarLee Robinson <me@leerob.io>

* refactor api methods

* fix: blog title

* fix: html lang

* next-mdx to gray-matter
Co-authored-by: 's avatarNoah Fischer <78238464+noahfschr@users.noreply.github.com>
Co-authored-by: 's avatarLee Robinson <me@leerob.io>
Co-authored-by: 's avatarEnes Akar <enesakar@gmail.com>
parent 82279730
REDIS_URL=
NEXT_PUBLIC_AUTH0_CLIENT_ID=
NEXT_PUBLIC_AUTH0_DOMAIN=
NEXT_PUBLIC_AUTH0_ADMIN_EMAIL=
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
{
"singleQuote": true,
"semi": false
}
# Blog with Comment
This project adds commenting functionality to [Next.js blog application](https://github.com/vercel/next.js/tree/canary/examples/blog) using Upstash and Auth0.
The comment box requires Auth0 authentication for users to add new comments. A user can delete their own comment. Also admin user can delete any comment.
Comments are stored in Serverless Redis ([Upstash](http://upstash.com/)).
### Demo
[https://blog-with-comment.vercel.app/](https://blog-with-comment.vercel.app/)
## `1` Project set up
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app)
with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the
example:
```bash
npx create-next-app --example blog-with-comment blog-with-comment-app
```
## `2` Set up environment variables
Copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):
```bash
cp .env.local.example .env.local
```
## `3` Configuring Upstash
Go to the [Upstash Console](https://console.upstash.com/) and create a new database
#### Upstash environment
- `REDIS_URL`: Find the URL in the database details page in Upstash Console clicking on **Redis Connect** button.
## `4` Configuring Auth0
1. Go to the [Auth0 dashboard](https://manage.auth0.com/) and create a new application of type **Single Page Web
Applications**.
2. Go to the settings page of the application
3. Configure the following settings:
- **Allowed Callback URLs**: Should be set to `http://localhost:3000/` when testing locally or typically
to `https://myapp.com/` when deploying your application.
- **Allowed Logout URLs**: Should be set to `http://localhost:3000/` when testing locally or typically
to `https://myapp.com/` when deploying your application.
4. Save the settings.
#### Auth0 environment
- `NEXT_PUBLIC_AUTH0_DOMAIN`: Can be found in the Auth0 dashboard under `settings`.
- `NEXT_PUBLIC_AUTH0_CLIENT_ID`: Can be found in the Auth0 dashboard under `settings`.
- `NEXT_PUBLIC_AUTH0_ADMIN_EMAIL`: This is the email of the admin user which you use while singing in Auth0. Admin is able to delete any comment.
## Deploy Your Local Project
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket
and [import to Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=upstash-roadmap).
**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to
match your `.env.local` file.
---
title: "A Long-expected Party"
excerpt: "Gandalf arrives in the Shire for Bilbo's Farewell Birthday Party.
Bilbo leaves the Shire permanently."
date: "2021-03-02"
---
Placeat consequuntur ullam aut sapiente illo velit. Eius facere ut molestias
totam laborum pariatur quam. Praesentium quo veritatis expedita animi.
Quite anything glass benefit. Such form clearly top tend can require my. Federal
degree sort performance region maintain.
Ut dignissimos sapiente culpa rerum pariatur consequatur. Corporis suscipit ad
corrupti aut. Expedita culpa aut deleniti officiis.
Porro eum id sit quia expedita. Alias expedita asperiores. Corporis ex eum atque
cum ea.
---
title: "The Passing of the Grey Company"
excerpt: "Aragorn, Legolas, and Gimli are accompanied by the Grey Company as
they pass through the Paths of the Dead between Rohan and Gondor."
date: "2021-01-22"
---
Placeat consequuntur ullam aut sapiente illo velit. Eius facere ut molestias
totam laborum pariatur quam. Praesentium quo veritatis expedita animi.
Quite anything glass benefit. Such form clearly top tend can require my. Federal
degree sort performance region maintain.
Ut dignissimos sapiente culpa rerum pariatur consequatur. Corporis suscipit ad
corrupti aut. Expedita culpa aut deleniti officiis.
Porro eum id sit quia expedita. Alias expedita asperiores. Corporis ex eum atque
cum ea.
---
title: "At the Sign of the Prancing Pony"
excerpt: "The Hobbits reach the The Prancing Pony inn at Bree, where Frodo uses
a false name, Underhill."
date: "2021-03-03"
---
Placeat consequuntur ullam aut sapiente illo velit. Eius facere ut molestias
totam laborum pariatur quam. Praesentium quo veritatis expedita animi.
Quite anything glass benefit. Such form clearly top tend can require my. Federal
degree sort performance region maintain.
Ut dignissimos sapiente culpa rerum pariatur consequatur. Corporis suscipit ad
corrupti aut. Expedita culpa aut deleniti officiis.
Porro eum id sit quia expedita. Alias expedita asperiores. Corporis ex eum atque
cum ea.
---
title: "The Riders of Rohan"
excerpt: "Aragorn, Legolas, and Gimli follow the trail of the Orcs and find
several clues as to what happened with Merry and Pippin."
date: "2021-02-01"
---
Placeat consequuntur ullam aut sapiente illo velit. Eius facere ut molestias
totam laborum pariatur quam. Praesentium quo veritatis expedita animi.
Quite anything glass benefit. Such form clearly top tend can require my. Federal
degree sort performance region maintain.
Ut dignissimos sapiente culpa rerum pariatur consequatur. Corporis suscipit ad
corrupti aut. Expedita culpa aut deleniti officiis.
Porro eum id sit quia expedita. Alias expedita asperiores. Corporis ex eum atque
cum ea.
import { useAuth0 } from '@auth0/auth0-react'
function CommentForm({ text, setText, onSubmit }) {
const { isAuthenticated, logout, loginWithPopup } = useAuth0()
return (
<form onSubmit={onSubmit}>
<textarea
className="flex w-full max-h-40 p-3 rounded resize-y bg-gray-200 text-gray-900 placeholder-gray-500"
rows="2"
placeholder={
isAuthenticated
? `What are your thoughts?`
: 'Please login to leave a comment'
}
onChange={(e) => setText(e.target.value)}
value={text}
disabled={!isAuthenticated}
/>
<div className="flex items-center mt-4">
{isAuthenticated ? (
<div className="flex items-center space-x-6">
<button className="py-2 px-4 rounded bg-blue-600 text-white disabled:opacity-40 hover:bg-blue-700">
Send
</button>
<button className="text-gray-500" onClick={() => logout()}>
Log out
</button>
</div>
) : (
<button
type="button"
className="py-2 px-4 rounded bg-blue-600 text-white disabled:opacity-40 hover:bg-blue-700"
onClick={() => loginWithPopup()}
>
Log In
</button>
)}
</div>
</form>
)
}
export default CommentForm
import CommentForm from './form'
import CommentList from './list'
import useComments from '../../hooks/useComment'
function Comment() {
const { text, setText, comments, onSubmit, onDelete } = useComments()
return (
<div className="mt-20">
<CommentForm onSubmit={onSubmit} text={text} setText={setText} />
<CommentList comments={comments} onDelete={onDelete} />
</div>
)
}
export default Comment
import distanceToNow from '../../lib/dateRelative'
import { useAuth0 } from '@auth0/auth0-react'
function CommentList({ comments, onDelete }) {
const { user } = useAuth0()
return (
<div className="space-y-6 mt-10">
{comments.map((comment) => {
const isAuthor = user && user.sub === comment.user.sub
const isAdmin =
user && user.email === process.env.NEXT_PUBLIC_AUTH0_ADMIN_EMAIL
return (
<div key={comment.created_at} className="flex space-x-4">
<div className="flex-shrink-0">
<img
src={comment.user.picture}
alt={comment.user.name}
width={40}
height={40}
className="rounded-full"
/>
</div>
<div className="flex-grow">
<div className="flex space-x-2">
<b>{comment.user.name}</b>
<time className="text-gray-400">
{distanceToNow(comment.created_at)}
</time>
{(isAdmin || isAuthor) && (
<button
className="text-gray-400 hover:text-red-500"
onClick={() => onDelete(comment)}
aria-label="Close"
>
x
</button>
)}
</div>
<div>{comment.text}</div>
</div>
</div>
)
})}
</div>
)
}
export default CommentList
function Container({ children }) {
return <div className="container max-w-2xl m-auto px-4">{children}</div>
}
export default Container
import Link from 'next/link'
import Container from '../components/container'
function Header() {
return (
<header className="py-6">
<Container>
<nav className="flex space-x-4">
<Link href="/">
<a>About</a>
</Link>
<Link href="/posts">
<a>Posts</a>
</Link>
</nav>
</Container>
</header>
)
}
export default Header
import { useState, useEffect } from 'react'
import useSWR from 'swr'
import { useAuth0 } from '@auth0/auth0-react'
export default function useComments() {
const { getAccessTokenSilently } = useAuth0()
const [text, setText] = useState('')
const [url, setUrl] = useState(null)
const { data: comments, mutate } = useSWR(
() => {
const query = new URLSearchParams({ url })
return `/api/comment?${query.toString()}`
},
{
initialData: [],
}
)
useEffect(() => {
const url = window.location.origin + window.location.pathname
setUrl(url)
}, [])
const onSubmit = async (e) => {
e.preventDefault()
const token = await getAccessTokenSilently()
try {
await fetch('/api/comment', {
method: 'POST',
body: JSON.stringify({ url, text }),
headers: {
Authorization: token,
'Content-Type': 'application/json',
},
})
setText('')
await mutate()
} catch (err) {
console.log(err)
}
}
const onDelete = async (comment) => {
const token = await getAccessTokenSilently()
try {
await fetch('/api/comment', {
method: 'DELETE',
body: JSON.stringify({ url, comment }),
headers: {
Authorization: token,
'Content-Type': 'application/json',
},
})
await mutate()
} catch (err) {
console.log(err)
}
}
return { text, setText, comments, onSubmit, onDelete }
}
import redis from './redis'
import { nanoid } from 'nanoid'
import getUser from './getUser'
export default async function createComments(req, res) {
const { url, text } = req.body
const { authorization } = req.headers
if (!url || !text || !authorization) {
return res.status(400).json({ message: 'Missing parameter.' })
}
try {
// verify user token
const user = await getUser(authorization)
if (!user) return res.status(400).json({ message: 'Need authorization.' })
const { name, picture, sub, email } = user
const comment = {
id: nanoid(),
created_at: Date.now(),
url,
text,
user: { name, picture, sub, email },
}
// write data
await redis.lpush(url, JSON.stringify(comment))
return res.status(200).json(comment)
} catch (_) {
return res.status(400).json({ message: 'Unexpected error occurred.' })
}
}
import formatDistanceToNowStrict from 'date-fns/formatDistanceToNowStrict'
export default function distanceToNow(dateTime) {
return formatDistanceToNowStrict(dateTime, {
addSuffix: true,
})
}
import redis from './redis'
import getUser from './getUser'
export default async function deleteComments(req, res) {
const { url, comment } = req.body
const { authorization } = req.headers
if (!url || !comment || !authorization) {
return res.status(400).json({ message: 'Missing parameter.' })
}
try {
// verify user token
const user = await getUser(authorization)
if (!user) return res.status(400).json({ message: 'Invalid token.' })
comment.user.email = user.email
const isAdmin = process.env.NEXT_PUBLIC_AUTH0_ADMIN_EMAIL === user.email
const isAuthor = user.sub === comment.user.sub
if (!isAdmin && !isAuthor) {
return res.status(400).json({ message: 'Need authorization.' })
}
// delete
await redis.lrem(url, 0, JSON.stringify(comment))
return res.status(200).json()
} catch (err) {
return res.status(400)
}
}
import redis from './redis'
export default async function fetchComment(req, res) {
const { url } = req.query
if (!url) {
return res.status(400).json({ message: 'Missing parameter.' })
}
try {
// get data
const rawComments = await redis.lrange(url, 0, -1)
// string data to object
const comments = rawComments.map((c) => {
const comment = JSON.parse(c)
delete comment.user.email
return comment
})
return res.status(200).json(comments)
} catch (_) {
return res.status(400).json({ message: 'Unexpected error occurred.' })
}
}
import fs from 'fs'
import { join } from 'path'
import matter from 'gray-matter'
const postsDirectory = join(process.cwd(), '_posts')
export function getPostSlugs() {
return fs.readdirSync(postsDirectory)
}
export function getPostBySlug(slug, fields = []) {
const realSlug = slug.replace(/\.md$/, '')
const fullPath = join(postsDirectory, `${realSlug}.md`)
const fileContents = fs.readFileSync(fullPath, 'utf8')
const { data, content } = matter(fileContents)
const items = {}
// Ensure only the minimal needed data is exposed
fields.forEach((field) => {
if (field === 'slug') {
items[field] = realSlug
}
if (field === 'content') {
items[field] = content
}
if (data[field]) {
items[field] = data[field]
}
})
return items
}
export function getAllPosts(fields = []) {
const slugs = getPostSlugs()
const posts = slugs
.map((slug) => getPostBySlug(slug, fields))
// sort posts by date in descending order
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1))
return posts
}
export default async function getUser(token) {
const response = await fetch(
`https://${process.env.NEXT_PUBLIC_AUTH0_DOMAIN}/userinfo`,
{
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
}
)
return await response.json()
}
import remark from 'remark'
import html from 'remark-html'
export default async function markdownToHtml(markdown) {
const result = await remark().use(html).process(markdown)
return result.toString()
}
import Redis from 'ioredis'
function fixUrl(url) {
if (!url) {
return ''
}
if (url.startsWith('redis://') && !url.startsWith('redis://:')) {
return url.replace('redis://', 'redis://:')
}
if (url.startsWith('rediss://') && !url.startsWith('rediss://:')) {
return url.replace('rediss://', 'rediss://:')
}
return url
}
class ClientRedis {
constructor() {
throw new Error('Use Singleton.getInstance()')
}
static getInstance() {
if (!ClientRedis.instance) {
ClientRedis.instance = new Redis(fixUrl(process.env.REDIS_URL))
}
return ClientRedis.instance
}
}
const redis = ClientRedis.getInstance()
export default redis
{
"name": "blog-with-comment",
"version": "1.0.0",
"author": "Adem ilter <ademilter@gmail.com>",
"license": "MIT",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@auth0/auth0-react": "^1.4.0",
"@tailwindcss/typography": "^0.4.0",
"date-fns": "^2.19.0",
"gray-matter": "4.0.3",
"ioredis": "^4.27.1",
"nanoid": "^3.1.22",
"next": "^10.2.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"remark": "13.0.0",
"remark-html": "13.0.1",
"swr": "^0.5.5"
},
"devDependencies": {
"autoprefixer": "^10.2.5",
"postcss": "^8.2.13",
"prettier": "^2.2.1",
"tailwindcss": "^2.1.2"
}
}
import 'tailwindcss/tailwind.css'
import Head from 'next/head'
import Header from '../components/header'
import { Auth0Provider } from '@auth0/auth0-react'
export default function MyApp({ Component, pageProps }) {
return (
<Auth0Provider
clientId={process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID}
domain={process.env.NEXT_PUBLIC_AUTH0_DOMAIN}
>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My awesome blog</title>
</Head>
<Header />
<main className="py-14">
<Component {...pageProps} />
</main>
</Auth0Provider>
)
}
import NextDocument, { Html, Head, Main, NextScript } from 'next/document'
export default class MyDocument extends NextDocument {
static getInitialProps(ctx) {
return NextDocument.getInitialProps(ctx)
}
render() {
const meta = {
title: 'Next.js Blog Starter Kit',
description: 'Clone and deploy your own Next.js portfolio in minutes.',
}
return (
<Html lang="en" className="bg-white text-gray-700 antialiased">
<Head>
<meta charSet="utf-8" />
<meta name="robots" content="follow, index" />
<meta name="description" content={meta.description} />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import fetchComment from '../../lib/fetchComment'
import createComments from '../../lib/createComment'
import deleteComments from '../../lib/deleteComment'
export default async function handler(req, res) {
switch (req.method) {
case 'GET':
return fetchComment(req, res)
case 'POST':
return createComments(req, res)
case 'DELETE':
return deleteComments(req, res)
default:
return res.status(400).json({ message: 'Invalid method.' })
}
}
import Container from '../components/container'
import Image from 'next/image'
function HomePage() {
return (
<>
<Container>
<div className="space-y-6">
<h1 className="text-2xl font-bold">
Hey, I'm a Senior Software Engineer at Company. I enjoy working with
Next.js and crafting beautiful front-end experiences.
</h1>
<p>
This portfolio is built with Next.js and a library called next-mdx.
It allows you to write Markdown and focus on the content of your
portfolio.
</p>
<p>Deploy your own in a few minutes.</p>
</div>
</Container>
<div className="container max-w-4xl m-auto px-4 mt-20">
<Image
src="/desk.jpg"
alt="my desk"
width={1920 / 2}
height={1280 / 2}
/>
</div>
</>
)
}
export default HomePage
import { useRouter } from 'next/router'
import ErrorPage from 'next/error'
import Comment from '../../components/comment'
import Container from '../../components/container'
import distanceToNow from '../../lib/dateRelative'
import { getAllPosts, getPostBySlug } from '../../lib/getPost'
import markdownToHtml from '../../lib/markdownToHtml'
import Head from 'next/head'
export default function PostPage({ post }) {
const router = useRouter()
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />
}
return (
<Container>
<Head>
<title>{post.title} | My awesome blog</title>
</Head>
{router.isFallback ? (
<div>Loading…</div>
) : (
<div>
<article>
<header>
<h1 className="text-4xl font-bold">{post.title}</h1>
{post.excerpt ? (
<p className="mt-2 text-xl">{post.excerpt}</p>
) : null}
<time className="flex mt-2 text-gray-400">
{distanceToNow(new Date(post.date))}
</time>
</header>
<div
className="prose mt-10"
dangerouslySetInnerHTML={{ __html: post.content }}
/>
</article>
<Comment />
</div>
)}
</Container>
)
}
export async function getStaticProps({ params }) {
const post = getPostBySlug(params.slug, [
'slug',
'title',
'excerpt',
'date',
'content',
])
const content = await markdownToHtml(post.content || '')
return {
props: {
post: {
...post,
content,
},
},
}
}
export async function getStaticPaths() {
const posts = getAllPosts(['slug'])
return {
paths: posts.map(({ slug }) => {
return {
params: {
slug,
},
}
}),
fallback: false,
}
}
import Link from 'next/link'
import Container from '../../components/container'
import distanceToNow from '../../lib/dateRelative'
import { getAllPosts } from '../../lib/getPost'
export default function NotePage({ allPosts }) {
return (
<Container>
{allPosts.length ? (
allPosts.map((post) => (
<article key={post.slug} className="mb-10">
<Link as={`/posts/${post.slug}`} href="/posts/[slug]">
<a className="text-lg leading-6 font-bold">{post.title}</a>
</Link>
<p>{post.excerpt}</p>
<div className="text-gray-400">
<time>{distanceToNow(new Date(post.date))}</time>
</div>
</article>
))
) : (
<p>No blog posted yet :/</p>
)}
</Container>
)
}
export async function getStaticProps() {
const allPosts = getAllPosts(['slug', 'title', 'excerpt', 'date'])
return {
props: { allPosts },
}
}
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
module.exports = {
mode: 'jit',
purge: ['./pages/**/*.js', './components/**/*.js'],
variants: {
extend: {
opacity: ['disabled'],
},
},
plugins: [require('@tailwindcss/typography')],
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment