hackernews-react-graphql
Hacker News clone rewritten with universal JavaScript, using React and GraphQL.
Top Related Projects
The Fullstack Tutorial for GraphQL
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
A reference implementation of GraphQL for JavaScript
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
The React Framework
Quick Overview
Hackernews-react-graphql is a Hacker News clone built with React, Next.js, and GraphQL. It aims to demonstrate how to create a full-stack application using modern web technologies while replicating the functionality of the popular Hacker News website.
Pros
- Provides a comprehensive example of integrating React, Next.js, and GraphQL in a real-world application
- Implements server-side rendering for improved performance and SEO
- Includes a well-structured codebase that can serve as a learning resource for developers
- Demonstrates best practices for state management, routing, and API integration
Cons
- May be overwhelming for beginners due to the complexity of the tech stack
- Requires understanding of multiple technologies to fully grasp the project structure
- Limited documentation on project setup and configuration
- Some dependencies may become outdated over time, requiring maintenance
Code Examples
- GraphQL Query Example:
query NewsItems($type: FeedType!, $first: Int, $skip: Int) {
feed(type: $type, first: $first, skip: $skip) {
items {
id
title
url
score
by {
id
username
}
commentsCount
}
}
}
This GraphQL query fetches news items based on the feed type, with pagination support.
- React Component Example:
const NewsItem = ({ item }) => (
<div className="news-item">
<h2>{item.title}</h2>
<p>By: {item.by.username}</p>
<p>Score: {item.score}</p>
<p>Comments: {item.commentsCount}</p>
</div>
);
This React component renders a news item with its title, author, score, and comment count.
- Next.js API Route Example:
export default async function handler(req, res) {
const { type, page } = req.query;
const items = await fetchNewsItems(type, page);
res.status(200).json(items);
}
This Next.js API route handles requests for news items, fetching data based on the provided type and page parameters.
Getting Started
To run the project locally:
-
Clone the repository:
git clone https://github.com/clintonwoo/hackernews-react-graphql.git
-
Install dependencies:
cd hackernews-react-graphql npm install
-
Start the development server:
npm run dev
-
Open your browser and navigate to
http://localhost:3000
to view the application.
Competitor Comparisons
The Fullstack Tutorial for GraphQL
Pros of howtographql
- Comprehensive tutorial-style content covering GraphQL fundamentals and various implementations
- Multi-language support with tutorials for different tech stacks (React, Node.js, Ruby, etc.)
- Active community and regular updates to keep content current
Cons of howtographql
- Less focused on a single, complete application example
- May require more time investment to work through all tutorials
- Not a direct implementation of a Hacker News clone
Code Comparison
howtographql (React + Apollo tutorial):
const GET_FEED = gql`
{
feed {
id
links {
id
createdAt
url
description
}
}
}
`
hackernews-react-graphql:
const FEED_QUERY = gql`
query FeedQuery($type: FeedType!, $offset: Int, $limit: Int) {
feed(type: $type, offset: $offset, limit: $limit) {
...FeedEntry
}
}
${FEED_ENTRY_FRAGMENT}
`
The howtographql example shows a simpler query structure, while hackernews-react-graphql demonstrates a more advanced query with parameters and fragments, reflecting its focus on a complete application implementation.
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
Pros of Apollo Client
- More comprehensive and feature-rich GraphQL client library
- Extensive documentation and community support
- Seamless integration with various frameworks and state management solutions
Cons of Apollo Client
- Larger bundle size and potential performance overhead
- Steeper learning curve for beginners
- May be overkill for simpler GraphQL implementations
Code Comparison
Apollo Client setup:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
Hackernews React GraphQL setup:
import { GraphQLClient } from 'graphql-request';
const client = new GraphQLClient('https://api.example.com/graphql');
Apollo Client offers a more robust setup with built-in caching, while Hackernews React GraphQL uses a simpler client implementation.
Apollo Client provides a higher level of abstraction and more features out of the box, making it suitable for complex applications. Hackernews React GraphQL, on the other hand, offers a lightweight solution that may be more appropriate for smaller projects or those requiring a custom GraphQL implementation.
The choice between the two depends on the project's specific needs, team expertise, and desired level of control over the GraphQL implementation.
A reference implementation of GraphQL for JavaScript
Pros of graphql-js
- Official reference implementation of GraphQL for JavaScript
- Comprehensive and well-maintained, with regular updates
- Extensive documentation and community support
Cons of graphql-js
- Focused solely on GraphQL implementation, not a full-stack solution
- Steeper learning curve for beginners compared to hackernews-react-graphql
- Requires additional setup and integration for a complete application
Code Comparison
hackernews-react-graphql:
const schema = new GraphQLSchema({
query: QueryType,
mutation: MutationType,
});
graphql-js:
const schema = buildSchema(`
type Query {
hello: String
}
`);
The hackernews-react-graphql example shows a more structured approach to schema definition, while graphql-js demonstrates a simpler string-based schema creation method.
hackernews-react-graphql provides a full-stack boilerplate for building a Hacker News clone using React and GraphQL, making it easier to get started with a complete application. On the other hand, graphql-js offers a more flexible and foundational approach, allowing developers to build custom GraphQL implementations tailored to their specific needs.
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Pros of Prisma
- More comprehensive database toolkit with ORM, migrations, and data modeling
- Larger community and ecosystem with extensive documentation
- Supports multiple databases (PostgreSQL, MySQL, SQLite, etc.)
Cons of Prisma
- Steeper learning curve for developers new to ORMs
- Less focused on a specific use case (like building a Hacker News clone)
- May introduce additional complexity for simple projects
Code Comparison
Prisma schema definition:
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
Hackernews React GraphQL schema definition:
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
url: String!
votes: Int!
postedBy: User!
createdAt: DateTime!
}
The Prisma schema offers more detailed type definitions and database-specific features, while the Hackernews React GraphQL schema is more focused on the specific needs of a Hacker News clone.
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
Pros of graphql-engine
- Provides a full-featured GraphQL server with built-in authorization and database integration
- Offers real-time subscriptions and live queries out of the box
- Supports multiple databases and can be easily deployed as a standalone server or Docker container
Cons of graphql-engine
- Steeper learning curve due to its more complex architecture and feature set
- May be overkill for simple projects that don't require advanced features
- Less flexibility in customizing the GraphQL schema compared to a hand-coded solution
Code Comparison
hackernews-react-graphql:
const typeDefs = gql`
type Story {
id: Int!
title: String!
url: String
score: Int
by: User!
}
`;
graphql-engine:
tables:
- table:
schema: public
name: stories
object_relationships:
- name: user
using:
foreign_key_constraint_on: user_id
array_relationships: []
The hackernews-react-graphql example shows a GraphQL schema definition, while the graphql-engine example demonstrates table configuration in YAML, highlighting the different approaches to schema definition between the two projects.
The React Framework
Pros of Next.js
- More comprehensive framework with built-in routing, server-side rendering, and API routes
- Larger community and ecosystem, with extensive documentation and third-party integrations
- Regular updates and maintenance from Vercel, ensuring long-term support and improvements
Cons of Next.js
- Steeper learning curve due to its more complex architecture and features
- Less flexibility for custom setups, as it enforces certain conventions and structures
- Potentially heavier bundle size for simpler applications that don't utilize all features
Code Comparison
Next.js (pages/index.js):
export default function Home() {
return <h1>Welcome to Next.js!</h1>
}
Hackernews React GraphQL (src/components/Home.js):
const Home = () => (
<div>
<h1>Welcome to Hacker News!</h1>
<NewsFeed />
</div>
);
Next.js provides a more streamlined approach with file-based routing, while Hackernews React GraphQL requires manual routing setup. Next.js also offers built-in server-side rendering capabilities, whereas Hackernews React GraphQL focuses on client-side rendering with GraphQL integration. The Hackernews project provides a more specific implementation tailored to the Hacker News clone use case, while Next.js offers a more general-purpose framework for various web applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Hacker News Clone React/GraphQL
This project is a clone of hacker news rewritten with universal JavaScript, using React and GraphQL. It is intended to be an example or boilerplate to help you structure your projects using production-ready technologies.
Overview
Featuring
-
React - (UI Framework)
-
GraphQL - (Web Data API)
-
Apollo - (GraphQL Client/Server)
-
Next - (Routing, SSR, Hot Module Reloading, Code Splitting, Build tool uses Webpack)
-
TypeScript - (Static Types)
-
Webpack - (Module Bundler)
-
PostCSS - (CSS Processing)
-
Node.js - (Web Server)
-
Express - (Web App Server)
-
Passport - (Authentication)
-
ESLint - (Coding Best Practices/Code Highlighting)
-
Jest - (Tests)
-
Docker - (Container Deployment)
-
Optional - Yarn or Pnpm Package Manager - (Better Dependencies)
Benefits
Front End
- Declarative UI - (
react
) - Static Typing (
typescript
) - GraphQL Fragment Colocation - (
@apollo/client
) - Prefetch Page Assets - (
next
)
Server
- Universal JS - (
node
&express
) - Declarative GraphQL Schema - (
apollo-server
) - GraphQL Query Batching - (
apollo-server-express
) - GraphQL Stored Queries - (
apollo-server-express
) - Easy GraphiQL Include - (
apollo-server-express
) - Local Authentication Strategy - (
passport
) - Server Side Rendering - (
next
) - Code Splitting - (
next
) - Build to Static Website - (
next
) - Container Based Runtime - (
docker
)
Dev/Test
- Hot Module Reloading - (
next
) - Snapshot Testing - (
jest
) - GraphQL Playground - (
apollo-server-express
) - Faster Package Install - (
pnpm
/yarn
) - JS/TS Best Practices - (
eslint
)
Architecture Overview
server.ts
is the entry point. It uses Express and passes requests to Next. Next SSR renders the pages using getServerSideProps()
hook from Apollo helper. Therefore the app makes GraphQL requests on the client or server.
When the client loads the page it preloads next pages code from any <Link href="/">
. When the client navigates to the next page it only needs to make one GraphQL query to render. Great!
See more: Next.js, Apollo GraphQL Client
GraphQL: GraphQL-Tools by Apollo or GraphQL docs
Directory Structure
Each web page has a React component in pages
. Server code is in server
. Shared code that runs on client or server is in src
. Do not import from server
or pages
in src
to avoid running code in the wrong environment.
The project root contains config files such as TypeScript, Babel, ESLint, Docker, Flow, NPM, Yarn, Git.
How To Start
One Click Download & Run
You can download and run the repo with one command to rule them all:
git clone https://github.com/clintonwoo/hackernews-react-graphql.git && cd hackernews-react-graphql && npm install && npm start
Setup
Running the app in dev mode is fully featured including hot module reloading:
npm install
npm start
To run in production mode:
npm run build:prod && npm run start:prod
Configuration
The project runs out of the box with default settings (/src/config.ts
). You can include a .env file in your project root to configure settings (this is the 'dotenv' npm package). The .env file is included in .gitignore.
How To Test
Jest
npm test
This project uses Jest and can do snapshot testing of React components. Whenever a component is changed, please update the snapshots using npm test -- -u
or npx jest --updateSnapshot
.
How To Build For Deployment
npm run build:prod
: NextJS app with entry point server.ts
that uses Node.js/Express. Uses TypeScript compiler to transpile project src to build.
OR
npm run build-docker
Docker Container: Builds a docker container using Dockerfile.
Static Website (Optional)
NextJS lets us make a powerful static website but you need to consider if you need server side rendering.
npm run build-static-website
: Builds static website to /build/static
. Use a static web server eg. NGINX/Github Pages.
Contributing
Pull requests are welcome. File an issue for ideas, conversation or feedback.
Community
After you â Star this project, follow @ClintonDAnnolfo on Twitter.
Top Related Projects
The Fullstack Tutorial for GraphQL
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
A reference implementation of GraphQL for JavaScript
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
The React Framework
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot