01Work02Services03About04Experience05Resume06Writing07Contact
moaz007malik@gmail.com
LinkedIn ↗GitHub ↗X ↗
Have something in mind?Let's connect →
Lahore, Pakistanmoaz007malik@gmail.comLinkedIn ↗GitHub ↗X ↗Resume ↓© 2026 Moaz Munawar. All rights reserved.
← All postsNovember 30, 2026 · 8 min read

How I Built a National Government Platform with the MERN Stack (Digital Youth Hub)

How I built Pakistan's Digital Youth Hub for the PM Youth Programme from scratch on MERN, designed to handle data for over 1 million users.

MERNReactNode.jsMongoDBTypeScriptGovernmentScalabilityCase Study
How I Built a National Government Platform with the MERN Stack (Digital Youth Hub)

Written by

Moaz Munawar

Most MERN stack tutorials end at a to-do app. The Digital Youth Hub was the opposite end of the scale: a national government platform for the Prime Minister Youth Programme in Pakistan, live at pmyp.gov.pk, that handles data for over 1 million users. I built it from scratch at Corvit Networks using React, TypeScript, Tailwind CSS, Node.js, Express and MongoDB.

In this post I share how I approached building a large-scale government platform with the MERN stack: the architecture, authentication and roles, API design, scaling MongoDB, and the lessons I'd apply to any big public-facing web app. I'll keep internal details private, but the engineering decisions are worth sharing.

Digital Youth Hub homepage, Prime Minister Youth Programme platform built with MERN

The Digital Youth Hub, live at pmyp.gov.pk.

What the platform needed to do

The goal was one digital home for the programme where young people can register, access programme services and track their progress, while staff manage those services from their own dashboards. That translated into a few hard requirements:

  • Scale. The data model and APIs had to handle data for over 1 million users and keep growing.
  • Security. Personal data of citizens has to be protected at every layer.
  • Multiple roles. Different users and staff need different views and permissions.
  • Modularity. New government service modules should plug into the platform without rebuilding it.
  • Accessibility on any device. Many users are on phones and mobile data, so the frontend has to be responsive and light.

Starting from an empty repository meant I could design for these from day one instead of retrofitting them.

Why MERN for a government platform

People sometimes assume government systems must be built on heavyweight enterprise stacks. For this project MERN was a good fit:

  • One language end to end. TypeScript on the frontend and JavaScript or TypeScript on the backend means shared types, shared validation logic and faster development.
  • MongoDB's flexible documents. Programme services and user profiles evolve. A document model handles new fields and new service types without painful migrations.
  • Node.js for I/O-heavy APIs. Most requests read and write data and call other services, which is exactly what Node's non-blocking model handles well.
  • React for a component-driven UI. Dashboards, forms and service pages share a lot of building blocks.

Architecture overview

At a high level the platform has three layers:

  1. React frontend built with TypeScript and Tailwind CSS, with route-level code splitting and role-aware layouts.
  2. Express REST API that owns all business rules, authentication and authorization.
  3. MongoDB as the main data store, modelled around users, roles and service modules.

The API is stateless. Every request carries its own credentials, so any API instance can handle any request. That is the single most important property for scaling horizontally: when traffic grows, you add instances behind a load balancer instead of rewriting the app.

Digital Youth Hub MERN architecture: React frontend, stateless Express API and MongoDB

A stateless API between the React frontend and MongoDB, built to handle data for over 1 million users.

A modular backend

I organised the backend by feature module rather than by file type. Each module has its own routes, controllers, services, validation and models. A simplified view of the layout:

src/
  modules/
    auth/
    users/
    services/
    dashboard/
  middleware/
    authenticate.ts
    authorize.ts
    validate.ts
    errorHandler.ts
  lib/
    db.ts
    logger.ts

Shared concerns like authentication, authorization, validation and error handling live in middleware and are reused by every module. A new government service becomes a new folder that plugs into the same pipeline, which is what made the platform modular in practice and not just in a diagram.

Authentication and role-aware access

With citizen data involved, authentication was the first thing I built and the thing I reviewed most.

The principles I build authentication around:

  • Passwords are hashed with a slow, salted algorithm and never logged or returned.
  • Short-lived access tokens with a refresh flow, so a leaked token has a limited lifetime.
  • Every protected route checks the token and the user's current status, so disabled accounts lose access immediately.
  • Input is validated at the edge before it reaches business logic.
  • Rate limiting on auth endpoints to slow down brute-force attempts.

Authorization is permission-based. Instead of sprinkling role checks through the code, routes declare what they need:

router.get(
  '/dashboard/summary',
  authenticate,
  authorize('dashboard.read'),
  dashboardController.summary
);

router.patch(
  '/services/:id/status',
  authenticate,
  authorize('services.manage'),
  validate(updateStatusSchema),
  servicesController.updateStatus
);

The frontend reads the same permission list after login and uses it to build role-aware dashboards: a regular user sees their own profile and services, while staff roles see management views for the modules they are responsible for. The UI hides what you can't use, and the API enforces it regardless.

Express request pipeline with authentication, permission-based authorization and validation

Every protected route runs the same pipeline before it touches MongoDB.

Designing REST APIs that hold up at scale

When a collection holds data for over a million users, small API decisions have big consequences.

Always paginate

No list endpoint returns "everything". For large collections, cursor-based pagination stays fast regardless of how deep you go, unlike large skip values:

export async function listUsers(req: Request, res: Response) {
  const limit = Math.min(Number(req.query.limit) || 20, 100);
  const cursor = req.query.cursor as string | undefined;

  const filter = cursor ? { _id: { $lt: new Types.ObjectId(cursor) } } : {};
  const items = await User.find(filter)
    .sort({ _id: -1 })
    .limit(limit + 1)
    .select('name email role createdAt')
    .lean();

  const hasMore = items.length > limit;
  const page = hasMore ? items.slice(0, limit) : items;
  res.json({ items: page, nextCursor: hasMore ? page[page.length - 1]._id : null });
}

Return only what the screen needs

Projections (select) and lean() keep responses small and avoid building full Mongoose documents when you only need plain data. Smaller payloads matter a lot for users on mobile data.

Consistent responses and errors

Every endpoint returns the same envelope shape and every error goes through one error handler. That makes the frontend simpler and makes debugging production issues much faster.

Scaling MongoDB

The database is where scale shows up first. The practices that mattered most:

  • Index for your real queries. Every common filter and sort, like lookups by email, or filters by status and date, needs a supporting index. Unique indexes also enforce data integrity, for example one account per email.
  • Compound indexes in the right order. Put equality fields first, then sort fields, then range fields.
  • Use explain() before shipping a new query to confirm it uses an index instead of scanning the collection.
  • Aggregate on the database. Dashboard counts and summaries run as aggregation pipelines rather than loading documents into Node.
  • Design documents around access patterns. Data that is always read together lives together; data that grows without limit goes in its own collection.
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ role: 1, createdAt: -1 });
serviceApplicationSchema.index({ userId: 1, status: 1, createdAt: -1 });

A frontend built for real users

A government platform serves everyone, not just people with new laptops and fast connections. On the React side I focused on:

  • Responsive layouts with Tailwind CSS, designed mobile first.
  • Code splitting by route, so a user filling in a service form doesn't download the admin dashboard.
  • Clear forms with inline validation, because most user interaction on the platform is filling in information.
  • Loading and error states everywhere, so a slow network never leaves someone staring at a blank screen.
  • TypeScript types shared with API responses, which catches mismatches at build time instead of in production.

Security beyond login

Authentication is only one layer. Other measures I treat as standard on a platform like this one:

  • HTTPS everywhere and secure HTTP headers.
  • Strict CORS so only the platform's own frontend can call the API from a browser.
  • Server-side validation and sanitisation of every input, never trusting the client.
  • Secrets in environment variables, never in the repository.
  • Audit-friendly logging of sensitive actions without logging personal data itself.

Lessons from building at national scale

  1. Design for scale on day one, but keep it simple. A stateless API, good indexes and pagination take you very far before you need anything exotic.
  2. Modularity pays off fast. A clean module pattern made each new service quicker to ship than the last.
  3. Permissions, not roles, in your routes. It keeps access control maintainable as roles multiply.
  4. Think about the slowest device. Payload size and bundle size are accessibility issues on a public platform.
  5. Own the whole stack. Building frontend, backend and data model myself meant decisions in one layer were made with the others in mind.

Conclusion

Building the Digital Youth Hub from an empty repository to a live national platform handling data for over 1 million users showed me that the MERN stack can carry serious, public-facing government work when it's designed with care: stateless APIs, permission-based access, disciplined MongoDB indexing and a frontend built for every kind of user.

You can read the project summary on the Digital Youth Hub case study. If you're planning a large-scale web platform and want someone who has built one end to end, get in touch.

← OlderHiring a Full Stack Developer in Pakistan: What to Look For