Building a Simple Crypto Exchange App with Next.js and GraphQL
September 25th, 2024
In this blog post, we’ll walk through creating a simple cryptocurrency exchange app using Next.js for the frontend and GraphQL for the backend. This app will allow users to view cryptocurrency prices and simulate buying/selling transactions. Let’s get started!
Prerequisites
Before you begin, make sure you have the following installed:
- Node.js (with npm)
- Next.js (we’ll set this up in the project)
- GraphQL (we’ll set this up in the project)
Step 1: Set Up the Next.js Project
1. Create a New Next.js App
Open your terminal and run:
npx create-next-app crypto-exchange
cd crypto-exchange
2. Install Required Dependencies
You’ll need graphql
, apollo-client
, and some other packages for state management. Install them with:
npm install @apollo/client graphql
Step 2: Set Up Apollo Client
1. Create an Apollo Client Instance
Create a new file apollo-client.js
in the root of your project:
// apollo-client.js
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,litecoin&vs_currencies=usd',
cache: new InMemoryCache(),
});
export default client;
Step 3: Create a GraphQL Query
1. Create a Query to Fetch Crypto Prices
In the pages
directory, create a new file called index.js
and set up a basic GraphQL query:
// pages/index.js
import { useQuery, gql } from '@apollo/client';
import client from '../apollo-client';
const GET_CRYPTO_PRICES = gql
query {
bitcoin {
usd
}
ethereum {
usd
}
litecoin {
usd
}
}
;
export default function Home() {
const { loading, error, data } = useQuery(GET_CRYPTO_PRICES, { client });
if (loading) return
Loading...
;
if (error) return
Error: {error.message}
;
return (
Crypto Exchange
- Bitcoin: ${data.bitcoin.usd}
- Ethereum: ${data.ethereum.usd}
- Litecoin: ${data.litecoin.usd}
);
}
Step 4: Display Prices and Simulate Transactions
1. Add Functionality to Buy/Sell Crypto
Modify the index.js
file to add buttons for buying and selling cryptocurrencies:
const handleBuy = (currency) => {
alert(`You bought ${currency}!`);
};
const handleSell = (currency) => {
alert(You sold ${currency}!);
};
return (
Crypto Exchange
- Bitcoin: ${data.bitcoin.usd}
- Ethereum: ${data.ethereum.usd}
- Litecoin: ${data.litecoin.usd}
);
Step 5: Run Your App
1. Start Your Next.js App
Back in your terminal, run:
npm run dev
Navigate to http://localhost:3000 in your browser. You should see your simple crypto exchange app displaying current prices and allowing you to buy/sell.
Conclusion
Congratulations! You’ve built a simple cryptocurrency exchange app using Next.js and GraphQL. This project serves as a great starting point for exploring more advanced features, like user authentication, transaction history, and integrating real-time data with subscriptions.
Feel free to expand upon this app and customize it according to your needs. Happy coding!