On this learing project, the developed application uses a combination of Next.js server components, the better-sqlite3 library, and AWS S3 to create and manage posts.
-
Next.js Server Components: Server components in Next.js allow you to write code that runs on the server but can interact with client components. In this application, the
Postscomponent is a client component that uses thecreatePostserver action to create a new post. ThecreatePostaction receives form data, validates it, uploads an image to AWS S3, and stores the post data in a SQLite database. -
better-sqlite3: This is a library that provides a synchronous API for interacting with SQLite databases in Node.js. It's used in the
storePostfunction inlib/posts.jsto insert a new post into thepoststable in the SQLite database. ThestorePostfunction is called by thecreatePostserver action. -
useOptimistic: This is a custom React hook used in the
Postsclient component. It's used to optimistically update the UI when a post is liked or unliked. When the like button is clicked, theupdatePostfunction is called, which first updates the local state of the posts usingupdateOptimisiticPosts, then calls thetogglePostLikeStatusserver action to update the like status in the database. -
AWS S3: Amazon S3 (Simple Storage Service) is a service offered by Amazon Web Services that provides object storage through a web service interface. In this application, it's used to store the images for the posts. The
uploadImagefunction inlib/aws.jsis used to upload an image to S3. This function is called by thecreatePostserver action.
When a new post is created, the createPost server action is called with the form data. This action validates the form data, uploads the image to AWS S3 using the uploadImage function, and stores the post data in the SQLite database using the storePost function. The URL of the uploaded image is stored in the image_url column of the posts table.
Install project dependencies:
npm install
To run this project, you will need to add the following environment variables to your .env file
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_S3_BUCKET=
AWS_REGION=Client: React, Next.js.
Topics Learned:
useOptimisitc, data fetching and mutation
MIT