DeveloperBreeze

Nodejs Programming Tutorials, Guides & Best Practices

Explore 16+ expertly crafted nodejs tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Build a Custom Rate Limiter in Node.js with Redis

Tutorial April 04, 2025

// server.js
require("dotenv").config();
const express = require("express");
const rateLimiter = require("./rateLimiter");

const app = express();
const PORT = 3000;

app.use(rateLimiter(100, 3600)); // 100 requests/hour per IP

app.get("/", (req, res) => {
  res.send("Welcome! You're within rate limit.");
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Use Postman or curl:

GraphQL API Server with Node.js and Apollo Server

Code August 12, 2024
nodejs graphql

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Sample data
let books = [
    { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
    { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
];

// GraphQL schema definition
const typeDefs = gql`
    type Book {
        title: String!
        author: String!
    }

    type Query {
        books: [Book]
    }

    type Mutation {
        addBook(title: String!, author: String!): Book
    }
`;

// GraphQL resolvers
const resolvers = {
    Query: {
        books: () => books,
    },
    Mutation: {
        addBook: (_, { title, author }) => {
            const newBook = { title, author };
            books.push(newBook);
            return newBook;
        },
    },
};

// Create Apollo server
const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
    console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
  • Schema Definition: The typeDefs defines a simple schema with a Book type and queries to fetch books and add a new book.
  • Resolvers: Functions that resolve the queries and mutations. In this case, they return all books and add a new book to the list.