惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
Martin Fowler
Martin Fowler
Vercel News
Vercel News
U
Unit 42
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
阮一峰的网络日志
阮一峰的网络日志
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog RSS Feed
N
Netflix TechBlog - Medium
GbyAI
GbyAI
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
M
MIT News - Artificial intelligence
D
Docker
IT之家
IT之家
Stack Overflow Blog
Stack Overflow Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How We Migrated Bloom After from Vanilla JS to Next.js + ...
Chijioke Uzodinma · 2026-06-27 · via DEV Community

As part of Rise Academy's frontend program, students are grouped and assigned real projects to work on. My group was assigned Bloom After — and our task was to migrate its existing Vanilla JS frontend to Next.js with TypeScript. Not because the old one was broken, but because that's exactly the kind of thing you need to do once on a real codebase before you can say you actually know how. I was the one who set up the new project and made most of the architectural decisions, so this is a first-hand account of how we approached it.


Why We Migrated

Honestly? The legacy frontend still worked. This wasn't a "the codebase is on fire" situation — it was a deliberate learning exercise set by Rise Academy. Bloom After was one of three projects assigned across student groups, and the task was to migrate it to a modern stack. Part of the value of Rise Academy's program is that you work on real projects, not toy examples — so the problems you encounter are real too.

That said, the migration did surface real problems worth solving:

  • Inconsistent data shapes. Some backend responses used _id, others id. Some used desc, others description. Messy in any codebase, good to clean up.
  • Auth in localStorage. Fine for a learning project, but not a habit worth keeping — so we fixed it properly.
  • No enforced structure. As the team grew, having no patterns made it easy to do things differently every time.

The goal wasn't to rescue a broken app. It was to learn migration — and learn it on something real enough to matter.


The Setup Decisions I Made Before Anyone Wrote a Single Component

Before I let anyone start building, I made a few calls that I think saved us a lot of pain.

1. Keep CSS Class Names the Same

The legacy app had a full stylesheet. Rather than rewriting CSS, I told the team: keep every class name identical to what it was in the Vanilla JS version. We only import the CSS a page actually needs, not a global dump of everything.

This meant:

  • No duplicate styling work
  • No visual regressions from class name mismatches
  • Designers and devs could reference the same class names they already knew

2. Route Groups for Shared Layouts

Next.js App Router supports route groups — folders wrapped in parentheses that don't affect the URL but let you share layouts. I used this heavily:

app/
├── (public)/          # Marketing pages — shared public header
├── (admin)/           # Admin pages — shared admin header
└── (dashboard)/       # User dashboard — shared sidebar

Each group gets its own layout.tsx, so the right header/sidebar renders automatically without any conditional logic inside components.

3. Normalise the Data at the Type Layer

Before writing a single component, I created TypeScript interfaces that reflected what the data should look like — not what the backend was actually sending. Then I wrote normalisation utilities to map the messy API responses into clean, predictable shapes.

// types/course.ts
export interface Course {
  id: string;           // normalised from _id or id
  title: string;
  description: string;  // normalised from dead or description
  createdAt: string;
}

// utils/normalise.ts
export function normaliseCourse(raw: Record<string, unknown>): Course {
  return {
    id: (raw._id ?? raw.id) as string,
    title: raw.title as string,
    description: (raw.description ?? raw.dead) as string,
    createdAt: raw.createdAt as string,
  };
}

This is one of the biggest wins TypeScript gave us. Once the normalisation layer existed, every component downstream could trust the shape of its data.


Week 1: Foundation

The Index Page + First Components

I started with the index page to validate the setup end-to-end — routing, CSS imports, layout — before anyone else touched the codebase. Once that was solid, I built the first two shared components:

  • TeamMembers — displays the team section on the public-facing pages
  • SuggestionDrawer — a slide-in drawer for user suggestions

These were deliberately simple. I wanted them as reference points for how components should be structured in this project before other team members started contributing.

api.ts — The Single HTTP Client

Instead of letting every file do its own fetch, I created a centralised HTTP client:

// lib/api.ts
const BASE_URL = process.env.NEXT_PUBLIC_API_URL;

async function request<T>(
  method: string,
  endpoint: string,
  body?: unknown
): Promise<T> {
  const res = await fetch(`${BASE_URL}${endpoint}`, {
    method,
    headers: { "Content-Type": "application/json" },
    body: body ? JSON.stringify(body) : undefined,
    credentials: "include",
  });

  if (!res.ok) throw new Error(`${method} ${endpoint}${res.status}`);
  return res.json();
}

export const api = {
  get: <T>(endpoint: string) => request<T>("GET", endpoint),
  post: <T>(endpoint: string, body: unknown) => request<T>("POST", endpoint, body),
  patch: <T>(endpoint: string, body: unknown) => request<T>("PATCH", endpoint, body),
  del: <T>(endpoint: string) => request<T>("DELETE", endpoint),
};

Then I created lifestyle-api.ts — a thin wrapper around api.ts that scoped all requests to the /lifestyle backend route. This gave other team members a focused, simple API surface for that part of the product without them needing to know the full backend structure.


Week 2: Admin, Auth, and Access Control

Reworking Authentication — localStorage → Cookies

The legacy frontend stored the auth token in localStorage. That's fine for simple apps, but it's vulnerable to XSS and it makes server-side auth checks impossible. I migrated to NextAuth with httpOnly cookies.

The key pieces:

Custom API routes for login/logout:

// app/api/auth/login/route.ts
import { cookies } from "next/headers";

export async function POST(req: Request) {
  const { email, password } = await req.json();

  const res = await fetch(`${process.env.API_URL}/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });

  if (!res.ok) return Response.json({ error: "Invalid credentials" }, { status: 401 });

  const { token } = await res.json();

  cookies().set("token", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
  });

  return Response.json({ ok: true });
}

// app/api/auth/logout/route.ts
import { cookies } from "next/headers";

export async function POST() {
  cookies().delete("token");
  return Response.json({ ok: true });
}

The token never touches the client — it lives in an httpOnly cookie the browser manages automatically.

Middleware for Protected Routes

Next.js middleware runs before a request hits any page. I used it to protect all admin routes:

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const token = request.cookies.get("token");

  if (!token) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/admin/:path*"],
};

Clean, centralised, impossible to bypass by navigating directly to a URL.

Admin Pages

With auth solid, I built out:

  • Admin Dashboard — overview metrics, quick actions
  • Admin Navbar + Sidebar — shared layout components inside (admin)/layout.tsx
  • Admin Renderers — reusable display components used across dashboard views
  • /admin/content-manager — lists all content pieces
  • /admin/content-manager/editor — full rich-text editor for creating and updating content

On the Deployment Strategy

I own all deployments — both the new Next.js frontend and the backend. The legacy Vanilla JS frontend is still live and running in parallel.

My personal take on how this should be handled: don't rush killing the legacy version. If I had the call, I'd keep both live for at least a month after the new one is stable, watch for unexpected errors, and only decommission the old one once we're confident. For a product with active users, the right approach is a gradual traffic migration — send a small percentage to the new frontend, validate it handles the load, then shift everyone over. Rushing that step is how you cause an outage.


What I'd Do Differently

  • Set up the normalisation layer before anything else, not alongside the first components. A week in, I was backfilling types for things I'd already built.
  • Document the route group structure on day one. A few teammates added pages in the wrong group early on because the convention wasn't written down yet.
  • Add a shared error boundary early. We added it later and had to retrofit it — easier to start with one.

Maintenance

The new frontend is now in active development. I maintain it going forward. The backend and legacy frontend are maintained by Grace.


Final Thoughts

Migrations are less about the code and more about the decisions you make before you write any. The CSS class naming convention, the route groups, the normalisation layer, the single HTTP client — none of those are complicated individually. Together, they made it possible for a small team to move fast without creating a new mess to replace the old one.

If you're planning a similar migration, the main thing I'd say is: design the constraints first, then build inside them.


Found this useful? Drop a reaction or share it — and feel free to ask questions in the comments.