In this workshop we'll learn how to build a full stack cloud application with Next.js, Tailwind, & AWS Amplify.
We'll start from scratch, creating a new Next.js app. We'll then, step by step, use the Amplify CLI to build out and configure our cloud infrastructure and then use the Amplify JS Libraries to connect the Next.js app to the APIs we create using the CLI.
The app will be a multi-user blogging platform with a markdown editor. When you think of many types of applications like Instagram, Twitter, or Facebook, they consist of a list of items and often the ability to drill down into a single item view. The app we will be building will be very similar to this, displaying a list of posts with data like the title, content, and author of the post.
This workshop should take you anywhere between 1 to 4 hours to complete.
- Getting Started
- Adding an API
- Adding authentication
- Enabling post creation
- Adding a my-posts view
- Updating and deleting posts
- Adding a cover image
- Deploying to AWS
- Removing services
Before we begin, make sure you have the following:
- Node.js v12.x or later installed
- A valid and confirmed AWS account
We will be working from a terminal using a Bash shell to run Amplify CLI commands to provision infrastructure and also to run a local version of the Next.js app and test it in a web browser.
This workshop is intended for intermediate to advanced front end & back end developers wanting to learn more about full stack serverless development.
While some level of React and GraphQL is helpful, this workshop requires zero previous knowledge about React or GraphQL.
- GraphQL API with AWS AppSync
- Authentication
- Authorization
- Hosting
- Deleting the resources
To get started, we first need to create a new Next.js project.
$ npx create-next-app amplify-next
Now change into the new app directory & install AWS Amplify, AWS Amplify UI React and a few other libraries we'll be using:
$ cd amplify-next
$ npm install aws-amplify @aws-amplify/ui-react [email protected] react-markdown uuid
Since we will be using Tailwind, let's also install the tailwind dependencies:
npm install tailwindcss@latest postcss@latest autoprefixer@latest @tailwindcss/typography
Next, create the necessary Tailwind configuration files:
npx tailwindcss init -p
Now update tailwind.config.js to add the Tailwind typography
plugin to the array of plugins:
plugins: [
require('@tailwindcss/typography')
],
Finally, replace the styles in styles/globals.css with the following:
@tailwind base;
@tailwind components;
@tailwind utilities;
Next, we'll install the AWS Amplify CLI:
# NPM
$ npm install -g @aws-amplify/cli
# cURL (Mac & Linux)
curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL
# cURL (Windows)
curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd
Now we need to configure the CLI with our credentials.
If you'd like to see a video walkthrough of this configuration process, click here.
$ amplify configure
- Specify the AWS Region: us-east-1 || us-west-2 || eu-central-1
- Specify the username of the new IAM user: amplify-cli-user
> In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, & Create User to create the new IAM user. Then return to the command line & press Enter.
- Enter the access key of the newly created user:
? accessKeyId: (<YOUR_ACCESS_KEY_ID>)
? secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>)
- Profile Name: amplify-cli-user
$ amplify init
- Enter a name for the project: amplifynext
- Initialize the project with the above configuration? No
- Enter a name for the environment: dev
- Choose your default editor: Visual Studio Code (or your default editor)
- Please choose the type of app that youre building: javascript
- What javascript framework are you using: react
- Source Directory Path: . (this sets the base directory to the root directory)
- Distribution Directory Path: .next
- Build Command: npm run-script build
- Start Command: npm run-script start
- Select the authentication method you want to use: AWS profile
- Please choose the profile you want to use: amplify-cli-user (or your preferred profile)
The Amplify CLI has initialized a new project & you will see a new folder: amplify & a new file called aws-exports.js
in the root directory. These files hold your project configuration.
To view the status of the amplify project at any time, you can run the Amplify status
command:
$ amplify status
To view the amplify project in the Amplify console at any time, run the console
command:
$ amplify console
To add a GraphQL API, we can use the following command:
$ amplify add api
? Please select from one of the above mentioned services: GraphQL
? Provide API name: NextBlog
? Choose the default authorization type for the API: API key
? Enter a description for the API key: public
? After how many days from now the API key should expire (1-365): 365 (or your preferred expiration)
? Do you want to configure advanced settings for the GraphQL API: No
? Do you have an annotated GraphQL schema? N
? Choose a schema template: Single object with fields
? Do you want to edit the schema now? (Y/n) Y
The CLI should open this GraphQL schema in your text editor.
amplify/backend/api/NextBlog/schema.graphql
Update the schema to the following:
type Post @model {
id: ID!
title: String!
content: String!
}
After saving the schema, go back to the CLI and press enter.
To deploy the API, run the push command:
$ amplify push
? Are you sure you want to continue? Y
# You will be walked through the following questions for GraphQL code generation
? Do you want to generate code for your newly created GraphQL API? Y
? Choose the code generation language target: javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions: ./graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2
Now the API is live and you can start interacting with it!
To test it out we can use the GraphiQL editor in the AppSync dashboard. To open the AppSync dashboard, run the following command:
$ amplify console api
> Choose GraphQL
In the AppSync dashboard, click on Queries to open the GraphiQL editor. In the editor, create a new post with the following mutation:
mutation createPost {
createPost(input: {
title: "My first post"
content: "Hello world!"
}) {
id
title
content
}
}
Then, query for the posts:
query listPosts {
listPosts {
items {
id
title
content
}
}
}
Now, our API is created & we can test it out in our app!
The first thing we need to do is to configure our Next.js app to be aware of our Amplify project. We can do this by referencing the auto-generated aws-exports.js
file that was created by the CLI.
Create a new file called configureAmplify.js in the root of the project and add the following code:
import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)
Next, open pages/_app.js and import the Amplify configuration below the last import:
import '../configureAmplify'
Now, our app is ready to start using our AWS services.
Now that the GraphQL API is running we can begin interacting with it. The first thing we'll do is perform a query to fetch data from our API.
To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.
The main thing to notice in this component is the API call. Take a look at this piece of code:
/* Call API.graphql, passing in the query that we'd like to execute. */
const postData = await API.graphql({ query: listPosts })
Open pages/index.js and add the following code:
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { API } from 'aws-amplify'
import { listPosts } from '../graphql/queries'
export default function Home() {
const [posts, setPosts] = useState([])
useEffect(() => {
fetchPosts()
}, [])
async function fetchPosts() {
const postData = await API.graphql({
query: listPosts
})
setPosts(postData.data.listPosts.items)
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-2">Posts</h1>
{
posts.map((post, index) => (
<Link key={index} href={`/posts/${post.id}`}>
<div className="cursor-pointer border-b border-gray-300 mt-8 pb-4">
<h2 className="text-xl font-semibold">{post.title}</h2>
</div>
</Link>)
)
}
</div>
)
}
Next, start the app:
$ npm run dev
You should be able to view the list of posts. You will not yet be able to click on a post to navigate to the detail view, that is coming up later.
Next, let's add some authentication.
To add the authentication service, run the following command using the Amplify CLI:
$ amplify add auth
? Do you want to use default authentication and security configuration? Default configuration
? How do you want users to be able to sign in when using your Cognito User Pool? Username
? Do you want to configure advanced settings? No, I am done.
To deploy the authentication service, you can run the push command:
$ amplify push
? Are you sure you want to continue? Yes
Next, let's add a profile screen and login flow to the app.
To do so, create a new file called profile.js in the pages directory. Here, add the following code:
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'
import { Auth } from 'aws-amplify'
import { useState, useEffect } from 'react'
function Profile() {
const [user, setUser] = useState(null)
useEffect(() => {
checkUser()
}, [])
async function checkUser() {
const user = await Auth.currentAuthenticatedUser()
setUser(user)
}
if (!user) return null
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6">Profile</h1>
<h3 className="font-medium text-gray-500 my-2">Username: {user.username}</h3>
<p className="text-sm text-gray-500 mb-6">Email: {user.attributes.email}</p>
<AmplifySignOut />
</div>
)
}
export default withAuthenticator(Profile)
The withAuthenticator
Amplify UI component will scaffold out an entire authentication flow to allow users to sign up and sign in.
The AmplifySignOut
button adds a pre-style sign out button.
Next, add some styling to the UI component by opening styles/globals.css and adding the following code:
:root {
--amplify-primary-color: #2563EB;
--amplify-primary-tint: #2563EB;
--amplify-primary-shade: #2563EB;
}
Next, open pages/_app.js to add some navigation and styling to be able to navigate to the new Profile page:
import '../styles/globals.css'
import '../configureAmplify'
import Link from 'next/link'
function MyApp({ Component, pageProps }) {
return (
<div>
<nav className="p-6 border-b border-gray-300">
<Link href="/">
<span className="mr-6 cursor-pointer">Home</span>
</Link>
<Link href="/create-post">
<span className="mr-6 cursor-pointer">Create Post</span>
</Link>
<Link href="/profile">
<span className="mr-6 cursor-pointer">Profile</span>
</Link>
</nav>
<div className="py-8 px-16">
<Component {...pageProps} />
</div>
</div>
)
}
export default MyApp
Next, run the app:
$ npm run dev
You should now be able to sign up and view your profile.
The link to /create-post will not yet work as we have not yet created this page.
Next, update the API to enable another authorization type to enable both public and private API access.
$ amplify update api
? Please select from one of the below mentioned services: GraphQL
? Select from the options below: Update auth settings
? Choose the default authorization type for the API: API key
? Enter a description for the API key: public
? After how many days from now the API key should expire (1-365): 365 <or your preferred expiration>
? Configure additional auth types? Y
? Choose the additional authorization types you want to configure for the API: Amazon Cognito User Pool
Next, let's update the GraphQL schema with the following changes:
- A new field (
username
) to identify the author of a post. - An
@key
directive for enabling a new data access pattern to query posts by username
Open amplify/backend/api/NextBlog/schema.graphql and update it with the following:
type Post @model
@key(name: "postsByUsername", fields: ["username"], queryField: "postsByUsername")
@auth(rules: [
{ allow: owner, ownerField: "username" },
{ allow: public, operations: [read] }
]) {
id: ID!
title: String!
content: String!
username: String
}
Next, deploy the updates:
$ amplify push --y
Now, you will have two types of API access:
- Private (Cognito) - to create a post, a user must be signed in. Once they have created a post, they can update and delete their own post. They can also read all posts.
- Public (API key) - Any user, regardless if they are signed in, can query for posts or a single post. Using this combination, you can easily query for just a single user's posts or for all posts.
To make this secondary private API call from the client, the authorization type needs to be specified in the query or mutation:
const postData = await API.graphql({
mutation: createPost,
authMode: 'AMAZON_COGNITO_USER_POOLS',
variables: {
input: postInfo
}
})
Next, create a new page at pages/create-post.js and add the following code:
import { withAuthenticator } from '@aws-amplify/ui-react'
import { useState } from 'react'
import { API } from 'aws-amplify'
import { v4 as uuid } from 'uuid'
import { useRouter } from 'next/router'
import SimpleMDE from "react-simplemde-editor"
import "easymde/dist/easymde.min.css"
import { createPost } from '../graphql/mutations'
const initialState = { title: '', content: '' }
function CreatePost() {
const [post, setPost] = useState(initialState)
const { title, content } = post
const router = useRouter()
function onChange(e) {
setPost(() => ({ ...post, [e.target.name]: e.target.value }))
}
async function createNewPost() {
if (!title || !content) return
const id = uuid()
post.id = id
await API.graphql({
query: createPost,
variables: { input: post },
authMode: "AMAZON_COGNITO_USER_POOLS"
})
router.push(`/posts/${id}`)
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6">Create new post</h1>
<input
onChange={onChange}
name="title"
placeholder="Title"
value={post.title}
className="border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
/>
<SimpleMDE value={post.content} onChange={value => setPost({ ...post, content: value })} />
<button
type="button"
className="mb-4 bg-blue-600 text-white font-semibold px-8 py-2 rounded-lg"
onClick={createNewPost}
>Create Post</button>
</div>
)
}
export default withAuthenticator(CreatePost)
This will render a form and a markdown editor, allowing users to create new posts.
Next, create a new folder in the pages directory called posts and a file called [id].js within that folder. In pages/posts/[id].js, add the following code:
import { API } from 'aws-amplify'
import { useRouter } from 'next/router'
import ReactMarkdown from 'react-markdown'
import '../../configureAmplify'
import { listPosts, getPost } from '../../graphql/queries'
export default function Post({ post }) {
const router = useRouter()
if (router.isFallback) {
return <div>Loading...</div>
}
return (
<div>
<h1 className="text-5xl mt-4 font-semibold tracking-wide">{post.title}</h1>
<p className="text-sm font-light my-4">by {post.username}</p>
<div className="mt-8">
<ReactMarkdown className='prose' children={post.content} />
</div>
</div>
)
}
export async function getStaticPaths() {
const postData = await API.graphql({
query: listPosts
})
const paths = postData.data.listPosts.items.map(post => ({ params: { id: post.id }}))
return {
paths,
fallback: true
}
}
export async function getStaticProps ({ params }) {
const { id } = params
const postData = await API.graphql({
query: getPost, variables: { id }
})
return {
props: {
post: postData.data.getPost
}
}
}
This page uses getStaticPaths
to dynamically create pages at build time based on the posts coming back from the API.
We also use the fallback
flag to enable fallback routes for dynamic SSG page generation.
getStaticProps
is used to enable the Post data to be passed into the page as props at build time.
Finally, update pages/index.js to add the author field and author styles:
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { API } from 'aws-amplify'
import { listPosts } from '../graphql/queries'
export default function Home() {
const [posts, setPosts] = useState([])
useEffect(() => {
fetchPosts()
}, [])
async function fetchPosts() {
const postData = await API.graphql({
query: listPosts
})
setPosts(postData.data.listPosts.items)
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-2">Posts</h1>
{
posts.map((post, index) => (
<Link key={index} href={`/posts/${post.id}`}>
<div className="cursor-pointer border-b border-gray-300 mt-8 pb-4">
<h2 className="text-xl font-semibold">{post.title}</h2>
<p className="text-gray-500 mt-2">Author: {post.username}</p>
</div>
</Link>)
)
}
</div>
)
}
Now the app is ready to test out, but before we do let's delete the existing data in the database that does not contain an author field. To do so, follow these steps:
- Open the Amplify Console
$ amplify console api
> Choose GraphQL
- Click on Data sources
- Click on the link to the database
- Click on the Items tab.
- Select the items in the database and delete them by choosing Delete from the Actions button.
Next, run the app:
$ npm run dev
You should be able to create new posts and view them dynamically.
To run a build and test it out, run the following:
$ npm run build
$ npm start
In a future step, we will be enabling the ability to edit or delete the posts that were created by the signed in user. Before we enable that functionality, let's first create a page for only viewing the posts created by the signed in user.
To do so, create a new file called my-posts.js in the pages directory. This page will be using the postsByUsername
query, passing in the username of the signed in user to query for only posts created by that user.
// pages/my-posts.js
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { API, Auth } from 'aws-amplify'
import { postsByUsername } from '../graphql/queries'
export default function MyPosts() {
const [posts, setPosts] = useState([])
useEffect(() => {
fetchPosts()
}, [])
async function fetchPosts() {
const { username } = await Auth.currentAuthenticatedUser()
const postData = await API.graphql({
query: postsByUsername, variables: { username }
})
setPosts(postData.data.postsByUsername.items)
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-2">My Posts</h1>
{
posts.map((post, index) => (
<Link key={index} href={`/posts/${post.id}`}>
<div className="cursor-pointer border-b border-gray-300 mt-8 pb-4">
<h2 className="text-xl font-semibold">{post.title}</h2>
<p className="text-gray-500 mt-2">Author: {post.username}</p>
</div>
</Link>)
)
}
</div>
)
}
Next, we need to update the nav to show the link to the new my-posts page, but only show the link if there is a signed in user.
To do so, we'll be using a combination of the Auth
class as well as Hub
which allows us to listen to authentication events.
Open pages/_app.js and make the following updates:
- Import the
useState
anduseEffect
hooks from React as well as theAuth
andHub
classes from AWS Amplify:
import { useState, useEffect } from 'react'
import { Auth, Hub } from 'aws-amplify'
- In the
MyApp
function, create some state to hold the signed in user state:
const [signedInUser, setSignedInUser] = useState(false)
- In the
MyApp
function, create a function to detect and maintain user state and invoke it in auseEffect
hook:
useEffect(() => {
authListener()
})
async function authListener() {
Hub.listen('auth', (data) => {
switch (data.payload.event) {
case 'signIn':
return setSignedInUser(true)
case 'signOut':
return setSignedInUser(false)
}
})
try {
await Auth.currentAuthenticatedUser()
setSignedInUser(true)
} catch (err) {}
}
- In the navigation, add a link to the new route to show only if a user is currently signed in:
{
signedInUser && (
<Link href="/my-posts">
<span className="mr-6 cursor-pointer">My Posts</span>
</Link>
)
}
Next, test it out by restarting the dev server:
npm run dev
Next, let's add a way for a signed in user to edit and delete their posts.
First, create a new folder named edit-post in the pages directory. Then, create a file named [id].js in this folder.
In this file, we'll be accessing the id
of the post from a route parameter. When the component loads, we will then use the post id from the route to fetch the post data and make it available for editing.
In this file, add the following code:
// pages/edit-post/[id].js
import { useEffect, useState } from 'react'
import { API } from 'aws-amplify'
import { useRouter } from 'next/router'
import SimpleMDE from "react-simplemde-editor"
import "easymde/dist/easymde.min.css"
import { updatePost } from '../../graphql/mutations'
import { getPost } from '../../graphql/queries'
function EditPost() {
const [post, setPost] = useState(null)
const router = useRouter()
const { id } = router.query
useEffect(() => {
fetchPost()
async function fetchPost() {
if (!id) return
const postData = await API.graphql({ query: getPost, variables: { id }})
setPost(postData.data.getPost)
}
}, [id])
if (!post) return null
function onChange(e) {
setPost(() => ({ ...post, [e.target.name]: e.target.value }))
}
const { title, content } = post
async function updateCurrentPost() {
if (!title || !content) return
await API.graphql({
query: updatePost,
variables: { input: { title, content, id } },
authMode: "AMAZON_COGNITO_USER_POOLS"
})
console.log('post successfully updated!')
router.push('/my-posts')
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-2">Edit post</h1>
<input
onChange={onChange}
name="title"
placeholder="Title"
value={post.title}
className="border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
/>
<SimpleMDE value={post.content} onChange={value => setPost({ ...post, content: value })} />
<button
className="mb-4 bg-blue-600 text-white font-semibold px-8 py-2 rounded-lg"
onClick={updateCurrentPost}>Update Post</button>
</div>
)
}
export default EditPost
Next, open pages/my-posts.js. We'll make a few updates to this page:
- Create a function for deleting a post
- Add a link to edit the post by navigating to
/edit-post/:postID
- Add a link to view the post
- Create a button for deleting posts
Update this file with the following code:
// pages/my-posts.js
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { API, Auth } from 'aws-amplify'
import { postsByUsername } from '../graphql/queries'
import { deletePost as deletePostMutation } from '../graphql/mutations'
export default function MyPosts() {
const [posts, setPosts] = useState([])
useEffect(() => {
fetchPosts()
}, [])
async function fetchPosts() {
const { username } = await Auth.currentAuthenticatedUser()
const postData = await API.graphql({
query: postsByUsername, variables: { username }
})
setPosts(postData.data.postsByUsername.items)
}
async function deletePost(id) {
await API.graphql({
query: deletePostMutation,
variables: { input: { id } },
authMode: "AMAZON_COGNITO_USER_POOLS"
})
fetchPosts()
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-2">My Posts</h1>
{
posts.map((post, index) => (
<div key={index} className="border-b border-gray-300 mt-8 pb-4">
<h2 className="text-xl font-semibold">{post.title}</h2>
<p className="text-gray-500 mt-2 mb-2">Author: {post.username}</p>
<Link href={`/edit-post/${post.id}`}><a className="text-sm mr-4 text-blue-500">Edit Post</a></Link>
<Link href={`/posts/${post.id}`}><a className="text-sm mr-4 text-blue-500">View Post</a></Link>
<button
className="text-sm mr-4 text-red-500"
onClick={() => deletePost(post.id)}
>Delete Post</button>
</div>
))
}
</div>
)
}
The last thing we need to do is implement Incremental Static Generation. Since we are allowing users to update posts, we need to have a way for our site to render the newly updated posts.
Incremental Static Regeneration allows you to update existing pages by re-rendering them in the background as traffic comes in.
To enable this, open pages/posts/[id].js and update the getStaticProps
method with the following:
export async function getStaticProps ({ params }) {
const { id } = params
const postData = await API.graphql({
query: getPost, variables: { id }
})
return {
props: {
post: postData.data.getPost
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every second
revalidate: 1 // adds Incremental Static Generation, sets time in seconds
}
}
To test it out, restart the server or run a new build:
npm run dev
# or
npm run build && npm start
Next, let's give users the ability to add a cover image to their post.
To do so, we need to do the following things:
- Add the
storage
category to the Amplify project. - Update the GraphQL schema to add a
coverImage
field to thePost
type - Update the UI to enable users to upload images
- Update the UI to render the cover image (if it exists)
To get started, let's first open the GraphQL schema located at amplify/backend/api/NextBlog/schema.graphql and add a coverImage
field:
type Post @model
@key(name: "postsByUsername", fields: ["username"], queryField: "postsByUsername")
@auth(rules: [
{ allow: owner, ownerField: "username" },
{ allow: public, operations: [read] }
]) {
id: ID!
title: String!
content: String!
username: String
coverImage: String
}
Next, enable file storage by running the Amplify add
command:
amplify add storage
? Please select from one of the below mentioned services: Content (Images, audio, video, etc.)
? Please provide a friendly name for your resource that will be used to label this category in the project: projectimages
? Please provide bucket name: <your-globally-unique-bucket-name>
? Who should have access: Auth and guest users
? What kind of access do you want for Authenticated users? create/update, read, delete
? What kind of access do you want for Guest users? read
? Do you want to add a Lambda Trigger for your S3 Bucket? No
Next, deploy the back end:
amplify push --y
Next, let's enable the ability to upload a cover image when creating a post.
To do so, open pages/create-post.js.
We will be making the following updates.
- Adding a button to enable users to upload a file and save it in the local state
- Import the Amplify
Storage
category anduseRef
from React. - When creating a new post, we will check to see if there is an image in the local state, and if there is then upload the image to S3 and store the image key along with the other post data.
- When a user uploads an image, show a preview of the image in the UI
// pages/create-post.js.
import { withAuthenticator } from '@aws-amplify/ui-react'
import { useState, useRef } from 'react' // new
import { API, Storage } from 'aws-amplify'
import { v4 as uuid } from 'uuid'
import { useRouter } from 'next/router'
import SimpleMDE from "react-simplemde-editor"
import "easymde/dist/easymde.min.css"
import { createPost } from '../graphql/mutations'
const initialState = { title: '', content: '' }
function CreatePost() {
const [post, setPost] = useState(initialState)
const [image, setImage] = useState(null)
const hiddenFileInput = useRef(null);
const { title, content } = post
const router = useRouter()
function onChange(e) {
setPost(() => ({ ...post, [e.target.name]: e.target.value }))
}
async function createNewPost() {
if (!title || !content) return
const id = uuid()
post.id = id
// If there is an image uploaded, store it in S3 and add it to the post metadata
if (image) {
const fileName = `${image.name}_${uuid()}`
post.coverImage = fileName
await Storage.put(fileName, image)
}
await API.graphql({
query: createPost,
variables: { input: post },
authMode: "AMAZON_COGNITO_USER_POOLS"
})
router.push(`/posts/${id}`)
}
async function uploadImage() {
hiddenFileInput.current.click();
}
function handleChange (e) {
const fileUploaded = e.target.files[0];
if (!fileUploaded) return
setImage(fileUploaded)
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6">Create new post</h1>
<input
onChange={onChange}
name="title"
placeholder="Title"
value={post.title}
className="border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
/>
{
image && (
<img src={URL.createObjectURL(image)} className="my-4" />
)
}
<SimpleMDE value={post.content} onChange={value => setPost({ ...post, content: value })} />
<input
type="file"
ref={hiddenFileInput}
className="absolute w-0 h-0"
onChange={handleChange}
/>
<button
className="bg-purple-600 text-white font-semibold px-8 py-2 rounded-lg mr-2"
onClick={uploadImage}
>
Upload Cover Image
</button>
<button
type="button"
className="mb-4 bg-blue-600 text-white font-semibold px-8 py-2 rounded-lg"
onClick={createNewPost}
>Create Post</button>
</div>
)
}
export default withAuthenticator(CreatePost)
Now, users should be able to upload a cover image along with their post. If there is a cover image present, it will show them a preview.
Next, let's look at how to render the cover image. To do so, we need to check to see if the cover image key exists as part of the post. If it does, we will fetch the image from S3 and render it in the view.
Update pages/posts/[id].js with the following:
// pages/posts/[id].js
import { API, Storage } from 'aws-amplify'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactMarkdown from 'react-markdown'
import { listPosts, getPost } from '../../graphql/queries'
export default function Post({ post }) {
const [coverImage, setCoverImage] = useState(null)
useEffect(() => {
updateCoverImage()
}, [])
async function updateCoverImage() {
if (post.coverImage) {
const imageKey = await Storage.get(post.coverImage)
setCoverImage(imageKey)
}
}
console.log('post: ', post)
const router = useRouter()
if (router.isFallback) {
return <div>Loading...</div>
}
return (
<div>
<h1 className="text-5xl mt-4 font-semibold tracking-wide">{post.title}</h1>
{
coverImage && <img src={coverImage} className="mt-4" />
}
<p className="text-sm font-light my-4">by {post.username}</p>
<div className="mt-8">
<ReactMarkdown className='prose' children={post.content} />
</div>
</div>
)
}
export async function getStaticPaths() {
const postData = await API.graphql({
query: listPosts
})
const paths = postData.data.listPosts.items.map(post => ({ params: { id: post.id }}))
return {
paths,
fallback: true
}
}
export async function getStaticProps ({ params }) {
const { id } = params
const postData = await API.graphql({
query: getPost, variables: { id }
})
return {
props: {
post: postData.data.getPost
}
}
}
Next, let's enable users to edit a post that contains a cover image. To do so, we'll need to enable similar functionality as we did when allowing users to create a post with a cover image.
We'll need to detect whether a post has a cover image, but also whether they have uploaded a new cover image and save the update if they have done so.
To implement this, update pages/edit-post/[id].js with the following code:
// pages/edit-post/[id].js
import { useEffect, useState, useRef } from 'react'
import { API, Storage } from 'aws-amplify'
import { useRouter } from 'next/router'
import SimpleMDE from "react-simplemde-editor"
import "easymde/dist/easymde.min.css"
import { v4 as uuid } from 'uuid'
import { updatePost } from '../../graphql/mutations'
import { getPost } from '../../graphql/queries'
function EditPost() {
const [post, setPost] = useState(null)
const router = useRouter()
const { id } = router.query
const [coverImage, setCoverImage] = useState(null)
const [localImage, setLocalImage] = useState(null)
const fileInput = useRef(null)
useEffect(() => {
fetchPost()
async function fetchPost() {
if (!id) return
const postData = await API.graphql({ query: getPost, variables: { id }})
console.log('postData: ', postData)
setPost(postData.data.getPost)
if (postData.data.getPost.coverImage) {
updateCoverImage(postData.data.getPost.coverImage)
}
}
}, [id])
if (!post) return null
async function updateCoverImage(coverImage) {
const imageKey = await Storage.get(coverImage)
setCoverImage(imageKey)
}
async function uploadImage() {
fileInput.current.click();
}
function handleChange (e) {
const fileUploaded = e.target.files[0];
if (!fileUploaded) return
setCoverImage(fileUploaded)
setLocalImage(URL.createObjectURL(fileUploaded))
}
function onChange(e) {
setPost(() => ({ ...post, [e.target.name]: e.target.value }))
}
const { title, content } = post
async function updateCurrentPost() {
if (!title || !content) return
const postUpdated = {
id, content, title
}
// check to see if there is a cover image and that it has been updated
if (coverImage && localImage) {
const fileName = `${coverImage.name}_${uuid()}`
postUpdated.coverImage = fileName
await Storage.put(fileName, coverImage)
}
await API.graphql({
query: updatePost,
variables: { input: postUpdated },
authMode: "AMAZON_COGNITO_USER_POOLS"
})
console.log('post successfully updated!')
router.push('/my-posts')
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-2">Edit post</h1>
{
coverImage && <img src={localImage ? localImage : coverImage} className="mt-4" />
}
<input
onChange={onChange}
name="title"
placeholder="Title"
value={post.title}
className="border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
/>
<SimpleMDE value={post.content} onChange={value => setPost({ ...post, content: value })} />
<input
type="file"
ref={fileInput}
className="absolute w-0 h-0"
onChange={handleChange}
/>
<button
className="bg-purple-600 text-white font-semibold px-8 py-2 rounded-lg mr-2"
onClick={uploadImage}
>
Upload Cover Image
</button>
<button
className="mb-4 bg-blue-600 text-white font-semibold px-8 py-2 rounded-lg"
onClick={updateCurrentPost}>Update Post</button>
</div>
)
}
export default EditPost
Now, users should be able to edit the cover image if it exists, or add a cover image for posts that do not contain one.
The last thing we may want to do is give a preview of the cover image in the list of posts on the main index page.
To do so, let's update our code to see if there is a cover image associated with each post. If there is, we'll fetch the image from S3 and then render the post image if it exists.
To implement this, open pages/index.js and update it with the following code:
// pages/index.js
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { API, Storage } from 'aws-amplify'
import { listPosts } from '../graphql/queries'
export default function Home() {
const [posts, setPosts] = useState([])
useEffect(() => {
fetchPosts()
}, [])
async function fetchPosts() {
const postData = await API.graphql({
query: listPosts
})
const { items } = postData.data.listPosts
// Fetch images from S3 for posts that contain a cover image
const postsWithImages = await Promise.all(items.map(async post => {
if (post.coverImage) {
post.coverImage = await Storage.get(post.coverImage)
}
return post
}))
setPosts(postsWithImages)
}
return (
<div>
<h1 className="text-3xl font-semibold tracking-wide mt-6 mb-8">Posts</h1>
{
posts.map((post, index) => (
<Link key={index} href={`/posts/${post.id}`}>
<div className="my-6 pb-6 border-b border-gray-300 ">
{
post.coverImage && <img src={post.coverImage} className="w-56" />
}
<div className="cursor-pointer mt-2">
<h2 className="text-xl font-semibold">{post.title}</h2>
<p className="text-gray-500 mt-2">Author: {post.username}</p>
</div>
</div>
</Link>)
)
}
</div>
)
}
If you'd like to also have the same functionality to preview cover images in the my-posts.js view, try adding the same updates there.
To deploy to AWS hosting, follow the guide laid out here
If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the amplify remove
command:
$ amplify remove auth
$ amplify push
If you are unsure of what services you have enabled at any time, you can run the amplify status
command:
$ amplify status
amplify status
will give you the list of resources that are currently enabled in your app.
If you'd like to delete the entire project, you can run the delete
command:
$ amplify delete