,

Crash Course on Modern Redis: Building a Backend with Express, TypeScript, and Zod

Posted by


In this tutorial, we will be covering a crash course on Modern Redis with a backend using Express, TypeScript, and Zod. Redis is an open-source, in-memory data structure store that can be used as a database, cache, and message broker. Express is a popular web application framework for Node.js, while TypeScript is a superset of JavaScript that adds static typing to the language. Zod is a TypeScript-first schema declaration and validation library.

By the end of this tutorial, you will have a fully functional backend application that uses Redis for data storage and retrieval.

Step 1: Setting up the project

To begin, let’s create a new project folder and navigate into it:

mkdir redis-backend
cd redis-backend

Next, let’s initialize a new Node.js project using npm:

npm init -y

We’ll need to install the necessary dependencies, including Express, Redis, TypeScript, and Zod:

npm install express redis typescript @types/express zod

Additionally, we’ll need to install some development dependencies for TypeScript:

npm install --save-dev typescript ts-node nodemon @types/node

Now, let’s set up our TypeScript configuration file. Create a new file called tsconfig.json in the root of your project and add the following content:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": ["ESNext"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Step 2: Creating the Express server

Now, let’s create our Express server. Create a new folder called src in the root of your project, and within that folder, create a new file called server.ts. Add the following code to set up a basic Express server:

import express from 'express';

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

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

Step 3: Setting up Redis

Next, let’s set up Redis in our project. Redis can be used for caching, session management, and other data storage purposes. We’ll be using the ioredis package to interact with Redis. Install it by running:

npm install ioredis @types/ioredis

In your server.ts file, import ioredis and create a new Redis client:

import Redis from 'ioredis';

const redis = new Redis();

Step 4: Writing data to Redis

Now that we have our Redis client set up, let’s write some data to Redis. We’ll create an endpoint /add that accepts a key-value pair in the request body, and stores it in Redis.

app.use(express.json());

app.post('/add', (req, res) => {
  const { key, value } = req.body;

  redis.set(key, value);
  res.send('Data stored successfully');
});

Step 5: Reading data from Redis

Next, let’s create an endpoint /get that accepts a key in the request query parameters, retrieves the corresponding value from Redis, and sends it back in the response.

app.get('/get', (req, res) => {
  const key = req.query.key as string;

  redis.get(key, (err, value) => {
    if (err) {
      return res.status(500).send('Error retrieving data');
    }

    res.send(value);
  });
});

Step 6: Adding data validation with Zod

To ensure that the data being stored in Redis is valid, we can use Zod for schema validation. Let’s create a schema for our key-value pair:

import { z } from 'zod';

const DataSchema = z.object({
  key: z.string(),
  value: z.string()
});

Now, let’s update our /add endpoint to validate the incoming data before storing it in Redis:

app.post('/add', (req, res) => {
  const { key, value } = DataSchema.parse(req.body);

  redis.set(key, value);
  res.send('Data stored successfully');
});

Step 7: Running the server

To run the server, we can use the TypeScript compiler in watch mode along with nodemon for automatic server restarts. Update your package.json scripts:

{
  "scripts": {
    "start": "nodemon src/server.ts",
    "build": "tsc -p ."
  }
}

Now, start the server by running:

npm start

You should see the message Server is running on http://localhost:3000 in the console. You can now test the /add and /get endpoints using a tool like Postman or curl.

Congratulations! You’ve successfully created a backend application with Express, TypeScript, Redis, and Zod. This crash course should give you a good starting point for building more sophisticated applications with these technologies. Feel free to explore more features of Redis, Express, TypeScript, and Zod to enhance your backend development skills.

0 0 votes
Article Rating

Leave a Reply

13 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@nr7343
2 hours ago

In production i need close connection in evrey operation? Or redis client can be open always?

@ryannicoletti6325
2 hours ago

Isnt initializing a redis client on every single route you need it bad? Wouldnt it be better to do that somewhere else and bring in to the routes when you need it instead of initializing all over the place?

@biLLie_wiLLie
2 hours ago

Great video! I like your tutorials. Can you explain rabbitMQ? I heard it's an important thing but I never worked with it

@otisrancko
2 hours ago

this is just fire…🔥🔥🔥🔥

@swarnabhamajumder9561
2 hours ago

Awesome video sir. Will there be a whole of backend cours with typescript.

@concaption
2 hours ago

which termainal

@tamaniphiri
2 hours ago

Great stack indeed 👌 👍

@hoangkietnguyenhuu
2 hours ago

Cool like coca cola

@madmaxdev
2 hours ago

Cool!

@sunielsharma8142
2 hours ago

Nishant chahar

@minidragonlady
2 hours ago

Cool. More about redis in the future (like rate limiting etc.)?

@HenokGebresenbet
2 hours ago

subbed bro cool video😊

@saadowain3511
2 hours ago

Keep up ❤ well explained

13
0
Would love your thoughts, please comment.x
()
x