Building a Modern Full Stack Application Architecture with Next.js 15+
This article walks step by step through a modern full stack application architecture built with Next.js 15 together with technologies such as TypeScript, Server Actions, Server and Client Components, Auth.js, Tailwind CSS, Drizzle ORM, PostgreSQL and Docker.
For many years now, the React library has enjoyed great popularity in the frontend world. It lets developers create interactive user interfaces out of reusable components that can be combined with one another. Thanks to this modular approach, the application is scalable and easy to maintain.
Being a library, React leaves it to developers to pick additional tools for things like routing, state management, data fetching, caching or page rendering strategies. This flexibility offers plenty of freedom. In practice, however, it comes down to making architectural decisions: how to organize folders and files, which naming conventions to follow, how to secure the application at the SSR level, how to approach SEO and, last but not least, how to look after the developer experience. As a result, developers have to spend time setting up tools and reinventing solutions for common application requirements.
Introduction
Of the frameworks that provide such configuration and tooling “out of the box”, Next.js leads the field. It is currently the most mature framework, which makes it a rather obvious pick, particularly for React developers or anyone who wants to build applications within the React ecosystem.
Next.js treats server-side rendering (SSR) as its main rendering technique. It also supports static-site generation (SSG), incremental static regeneration (ISR) and client-side rendering (CSR). On top of that, it offers React Server Components (RSC) and React Server Functions (RSF) as fundamental architectural building blocks. Next.js also lets you combine these rendering techniques freely – a landing page can rely on SSG, for instance, while an application with authentication (a dashboard) can rely on SSR.
React on its own lets you build applications that run exclusively on the client side. If such an application needs a backend (to handle database queries or authentication, for example), that backend has to be built separately and integrated with the React application. Next.js, by contrast, makes it possible to build full-stack applications, letting the developer work on both the frontend and the backend within a single framework.
Key features of Next.js
- SSR – built-in support for server-side page rendering, which boosts performance and SEO
- SSG – support for static site generation, in which pages are produced at compile time and served as static HTML files, speeding up loading and lightening the server load
- Automatic code splitting – Next.js breaks code into smaller, more manageable chunks to optimize performance and loading time
- CSS support– support for a range of CSS solutions, including CSS modules, CSS-in-JS libraries and global CSS styles, offering flexibility in how the application is styled
- Data fetching – support for several ways of fetching data at compile time or at request time
- Routing – made much simpler by automatic route generation based on the file structure and page directories
- Image optimization – automatic resizing and compressing of images to ensure optimal loading performance
- Built-in CSS and JavaScript bundling – CSS and JS are optimized and bundled automatically so they load more efficiently
- API proxying – lets you create API routes that act as proxies for third-party APIs, helping with data fetching and security
- Internationalization support – Next.js offers tools and libraries for supporting multiple languages
Given these features and advantages, it’s worth asking when it makes sense to choose this framework over plain React. Next.js comes in handy for content-heavy websites such as blogs or e-commerce, where SEO also matters a lot. Next.js can noticeably improve application performance, since the user doesn’t have to download and execute large amounts of JS on their device – which matters particularly on slower devices or networks.
Sticking with plain React, then, is the better option when we are dealing with:
- A microservices architecture, or logic that relies heavily on the backend
- An application that depends heavily on real-time updates
- A highly customized user interface with things like animations, interactions and complex layouts
With the introduction behind us, it’s time to get down to specifics. I will go through the remaining concepts a developer should keep in mind when building a Next.js application by scaffolding and configuring an application that performs CRUD operations on articles, authentication included.
Starting the project
In the terminal:
npx create-next-app@latest
Once the command runs, we answer a few prompts, and shortly afterwards everything we need is configured automatically.
Project’s structure
One of the prompts asks which router to use. Next.js offers two kinds:
- App Router – the newer router, supporting new React features such as Server Components and Server Actions,
- Pages Router – relies on a file-system router that maps every file to a route. Until version 13, it was the primary way of creating routes, and newer versions still support it.
Before Next.js brought in the App Router, in-app routing was built on the Pages Router. Essentially, it relied on the React Router built into Next.js to handle navigation between pages automatically.
With the Pages Router technique, you create .js or .ts files in the pages directory, and Next.js automatically turns them into sub-pages of the application. Creating a structure like pages/users.ts, for example, produces a page at /users.
When a request needs to go to the server in the Pages Router, the getServerSideProps or getStaticProps methods can be used inside the pages files.
The App Router – the newer approach (since version 13) and the recommended one – gives developers more control and flexibility. It defines routes with directories, which enables more advanced features such as nested layouts.
Given an app/users/page.ts structure, the page is a server component by default (it runs on the server), and the /users path becomes the route. You can also create layouts shared across several routes, which helps keep the design and structure consistent across the whole application.
Next.js gives special meaning to certain reserved folder and file names. For folders, these include src, public, app, [folder], […folder]. For files, examples include (with the .ts, .js, .tsx, .jsx extensions respectively): middleware, layout, page, loading, error. Where they sit in the project structure decides how pages and components get rendered and how the application as a whole behaves.
You’ll find more details here: project structure and organization
Server Actions
In the newer approach, server-side work such as fetching data, submitting forms and interacting with the database is handled through Server Actions. In the App Router, every request is server-side by default, which makes it simpler to communicate with the server before the page renders. Server Actions can be invoked from both Server and Client Components.
Server Actions are declared with the ‘use server’ directive. Next.js needs to be told that a function, or every export in a file, should be treated as a Server Action. Without this directive, Next.js can’t tell whether a function is local (used by server components only) or whether it should be exposed as a Server Action that the client can call. That is by design, since Next.js lets you mix Client and Server Components in a hybrid way – and only functions marked with the ‘use server’ directive are callable from the client.
For instance:
'use server';
import { eq } from 'drizzle-orm';
import db from '@/db';
import { articles } from '@/db/schema';
export async function getArticleBySlug(slug: string) {
return await db.query.articles.findFirst({
where: eq(articles.slug, slug),
});
}
Thanks to the ‘use server’ directive, the getArticleBySlug function can be invoked from both:
Server Component:
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const data = await getArticleBySlug(slug);
// ...
}
and a Client Component (for example, by passing the function as a callback to an event handler or inside useEffect):
or:
'use client';
import { createArticle } from '@/lib/actions/article.actions';
// ...
export const ArticleForm = () => {
return (
<form action={createArticle}>
{/* ... */}
<button type='submit'>Create</button>
</form>
);
};
or:
'use client';
import { createArticle } from '@/lib/actions/article.actions';
// ...
export const ArticleForm = () => {
return (
<>
{/* ... */}
<button
onClick={async () => {
const formData = new FormData();
formData.append('title', 'Article title');
await createArticle(formData);
}}
>
Create
</button>
</>
);
};
Without the ‘use server’ directive, Next.js might treat such a function as a regular helper function. As a result, it would not be registered as a Server Action and could not be called dynamically from the Client Component.
The ‘use server’ directive can go either at the top of an asynchronous function, marking that function as a Server Action, or at the top of a separate file, marking every export of that file as a Server Action:
// Directive at the top of a separate file
'use server';
export async function createArticle(article: Article): Promise<ReturnType> {
const parsedArticle = articleFormSchema.parse(article);
if (!parsedArticle.success) return { message: 'Something went wrong' };
return { message: 'Article created' };
}
// Directive at the top of an async function
export function Page() {
const createArticle = async () => {
'use server';
// ...
};
return <form action={createArticle}>...</form>;
}
Server and Client Components
Let’s now tackle the question of when to reach for Client and when for Server Components.
Layouts and pages are Server Components by default. This lets you send requests from the server and render parts of the user interface there, optionally caching the results and passing them to the client. Client Components, on the other hand, are the choice when you need interactivity or access to the browser API. To create a Client Component, you add a ‘use client’ directive at the top of the file, above the imports. Once a file carries the ‘use client’ directive, everything it imports and all its subcomponents become part of the client bundle. This also means you don’t have to put a ‘use client’ directive in every component meant for the client.
When to use Client Components:
- Managing component state and handling events (e.g. onClick, onChange)
- Using the component lifecycle (e.g. useEffect)
- Accessing the browser API (localStorage, window, geolocation)
- Custom hooks
When to use Server Components:
- Talking to the database
- Working with API keys, tokens and other sensitive data the client should not have access to
- Reducing the amount of JavaScript shipped to the browser
- Improving First Contentful Paint and streaming content to the client progressively
Package manager
To initialize the project, we used the npx command, which runs Node.js packages from the npm registry on the fly without installing them globally. When it comes to package managers, npm is the most widely used, largely because it ships with every Node.js installation. Still, yarn, pnpm and bun are solid alternatives – pnpm in particular, thanks to its better performance.
If you ever need to build several applications that depend on one another or share a common set of components, a monorepo is worth considering. Tools such as Nx or Turborepo can work well for this.
Linter and code formatter
With the project initialized, the next step worth taking is ensuring a consistent code style. The ESLint linter helps here: it enforces a particular code style and flags an error in our IDE whenever the defined rules are broken.
It should be complemented by a code formatter such as Prettier, which can be set up to format the code – following specific rules – each time a file is saved. Prettier doesn’t replace ESLint, but the two integrate nicely.
Install the package with:
npm install --save-dev eslint-config-prettier
Then add the package to the ESLint configuration file (eslint.config.mjs).
While you’re at it, don’t forget to install a package that sorts import declarations in a defined order. For instance, third-party libraries go first, then alias imports and finally relative imports, with blank lines separating the groups, which keeps this part of the file tidy and readable:
npm install --save-dev @trivago/prettier-plugin-sort-imports
Next, add the package to the plugins list in the .prettierrc.json file and define the sorting rules:
{
"importOrder": [
"^(react|next?/?([a-zA-Z/]*))$",
"<THIRD_PARTY_MODULES>",
"^@/(.*)$",
"^[./]"
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true,
"plugins": ["@trivago/prettier-plugin-sort-imports"]
}
Styling
The application comes ready for Tailwind CSS. Naturally, how you style the application depends on your needs and taste. Still, this framework deserves a try because of its approach to utility classes, which compose easily to build any project. What makes Tailwind CSS stand out is that rather than handing us ready-made components, it gives us the tools to build our own.
The traditional approach relied on classes such as container, section-wrapper, accordion, heading-1, notification and the like. Tailwind CSS has no classes of this kind; instead, it offers a set of simple tools like flex (which sets display: flex), w-screen (width: 100vw), text-lg (which sets both a specific font-size and a specific line-height) and so on. I recommend reading the documentation.
Different projects come with different user interface styling requirements, ranging from a defined design system that calls for custom components to a more flexible approach where off-the-shelf solutions will do. One of today’s popular component libraries is shadcn/ui, which builds ready-made components out of Tailwind primitive classes. What’s more, it isn’t installed as a project dependency; instead, the code is placed in the components directory, giving us access to the source. The shadcn/ui components ship with basic styling, so they are easy to adapt to the application’s design.
Other noteworthy libraries include:
Working with environment variables
Next, let’s look at setting up how we work with environment variables. By default, Next.js picks up the .env file in the project and loads the environment variables defined in it, making them available via process.env. It can happen, though, that a variable is missing or has the wrong type – a port number, for example, should be a number rather than a string. To handle environment variables in a type-safe manner with automatic validation, it’s worth turning to the Zod library, which lets us define a schema for the required variables and validate them when the application starts.
We can take this one step further, though, with the T3 Env library, which is built on Zod and designed specifically for managing environment variables in TypeScript/Next.js projects. It also lets us keep client-side and server-side variables apart.
Installation:
npm install @t3-oss/env-nextjs zod
In the src/env/server.ts file, we define a schema for the server-specific environment variables:
import { createEnv } from "@t3-oss/env-nextjs";
import "dotenv/config";
import { z } from "zod";
export const env = createEnv({
server: {
NODE_ENV: z.enum(["development", "production"]),
AUTH_GOOGLE_ID: z.string(),
AUTH_GOOGLE_SECRET: z.string(),
SESSION_SECRET: z.string(),
DATABASE_URL: z.string().url(),
CLOUDINARY_NAME: z.string(),
CLOUDINARY_KEY: z.string(),
CLOUDINARY_SECRET: z.string(),
},
onValidationError: (issues) => {
console.error("❌ Invalid environment variables:", issues);
process.exit(1);
},
emptyStringAsUndefined: true,
experimental__runtimeEnv: process.env,
});
If needed, I will keep a separate src/env/client.ts file for the client, since an environment variable has to carry the NEXTPUBLIC prefix to be exposed in the browser.
It’s a good idea to import this file into the next.config.ts file, so that the environment variables get checked at compile time. If any variable is missing, the application won’t start at all.
To stop our application from accessing process.env directly anywhere and to enforce the use of the schema we created, we can install the eslint-plugin-n plugin:
npm install –save-dev eslint-plugin-n
and enable it in the eslint.config.mjs file:
const eslintConfig = [
...compat.config({
plugins: ['n'],
rules: {
"n/no-process-env": ["error"]
}
})
];
From now on, referring to an environment variable requires importing the env constant we defined earlier:
import { env } from “@/env/server”;
and then using it:
env.DATABASE_URL
Handling forms and validations
Forms are an essential part of any application, and working with them brings a number of challenges. We need client-side validation to give users instant feedback, and server-side validation to guarantee data integrity and to manage form state. This can get complicated fast, especially with multi-step forms or forms with dynamic fields. Specialized libraries that offer a structured approach to validation, cut down on boilerplate and help keep the user interface consistent for error states and feedback can greatly improve both the developer and the user experience.
React Hook Form is a notable form library focused on performance. It is built to minimize re-rendering while staying flexible. Its hooks-first approach simplifies the component tree and avoids needless re-rendering.
Installation:
npm install react-hook-form
And here’s an example:
import { zodResolver } from "@hookform/resolvers/zod";
import { SubmitHandler, useForm } from "react-hook-form";
import { z } from "zod";
// ...
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(articleFormSchema),
defaultValues: { ... },
});
const onSubmit: SubmitHandler<z.infer<typeof articleFormSchema>> = async (
values
) => { ... };
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<Input {...register("title", { required: true })} />
<p>{errors.title?.message}</p>
</div>
{/* ... */}
</form>
);
};
React Hook Form plays nicely with schema validation libraries (the example above uses zodResolver). I brought up the Zod library when talking about environment variables, and it fits this case perfectly too. It is a TypeScript-first library that lets us define validation schemas through a chainable API built on TypeScript’s type inference system. A major strength of Zod is that it can act as the single source of truth for validation logic on both the client and the server, so we can define a validation schema once and reuse it across the whole application.
Example:
import { z } from "zod";
export const signUpFormSchema = z
.object({
name: z.string().min(3, "Name must be at least 3 characters"),
email: z.string().email("Invalid email address"),
password: z.string().min(6, "Password must be at least 6 characters"),
confirmPassword: z
.string()
.min(6, "Confirm password must be at least 6 characters"),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
});
For server-side validation, in turn, Zod offers a clean and straightforward way of validating a request’s payload:
import { signUpFormSchema } from "@/validations/sign-up.validator";
export async function signup(_state: FormState, formData: FormData) {
try {
const user = signUpFormSchema.parse({
name: formData.get("name"),
email: formData.get("email"),
password: formData.get("password"),
confirmPassword: formData.get("confirmPassword"),
});
// ...
} catch (error) {
// ...
}
}
Testing
Testing is built on a framework like Vitest or Jest, which supplies tools for running tests, an assertion library, and function spying and mocking. The React Testing Library is a useful complement, letting us render React components and simulate events on HTML elements.
For E2E testing, Playwright is the recommended tool, with Cypress as an alternative. Both let you automate and simulate user interactions in the browser to make sure the application behaves as intended.
Authentication
Next up is configuring authentication. Broadly speaking, authentication involves these concepts:
- Authentication: the process of confirming a user’s identity, i.e. checking that whoever is trying to access an application really is who they say they are
- Session management: keeping track of a user’s authentication status as they request resources
- Authorization: deciding which resources and operations a user can access once authenticated in an application
A project’s authentication can be set up in many ways. The Next.js documentation page has a whole article on building it from scratch, session management included. Starting from scratch won’t always be needed, however, so ready-made solutions are recommended, not least for better security and simplicity. Such libraries provide built-in authentication, session management and authorization, plus extras like social login, multi-factor authentication or role-based access control (RBAC). Next.js maintains a list of compatible authentication and session management libraries.
For our sample application, I’ll concentrate on Auth.js. It is a complete authentication solution that is built for Next.js but also works with other backend frameworks (before version 5 it was called NextAuth and supported only Next.js). It greatly cuts down the time required to implement secure authentication in a project.
Key features of Auth.js include:
- Out-of-the-box support for popular authentication providers (e.g. Google, GitHub, FaceBook)
- An email/password authentication option
- Thorough session management
- Role-based access control
- Security features such as CSRF protection and http-only cookies
I’ll use two authentication methods:
- Credentials provider – lets users log in with any credentials, such as email and password
- Google provider – lets users log in with a Google account
There are two kinds of sessions available for session management:
- Stateless – the session data lives in browser cookies. The cookie accompanies every request, so the server can verify it. It’s the simpler approach, but potentially less secure (this is the one I’ll use – JWT token
- Database – the session data lives in the database, and the user’s browser gets only an encrypted session ID. It’s more secure, but may be more complex and consume more server resources
Installation:
npm install next-auth@beta
Configuration in the @/auth.ts file:
import NextAuth, { type User } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
export const { handlers, signIn, signOut, auth } = NextAuth({
session: {
strategy: "jwt",
},
providers: [
GoogleProvider,
Credentials({
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
// ...
},
}),
],
});
Next, we can protect the route like this:
import { auth } from '@/auth';
// ...
const session = await auth();
if (!session?.user) {
return redirect('/sign-in');
}
More details on installing Auth.js are available here.
Database integration
Building a Next.js application usually means working with a database ORM. Of the several available, two are especially popular: Prisma and Drizzle ORM.
My choice is Drizzle ORM. What sets Drizzle apart is that it requires no code generation, unlike Prisma. With Prisma, you first define a schema and then run the npx prisma generate command (after every change to the schema file). That step produces the Prisma client (@prisma/client) and the model’s type definitions.
In Drizzle, defining a table in TypeScript simultaneously defines ready-to-use types, with no separate code generation commands to run. Consequently, changing the schema in Drizzle needs no extra step to refresh the types and the ORM client.
Drizzle also comes with built-in helper functions that turn those same table definitions into Zod validators (once again without extra code generation).
What’s more, Drizzle offers various adapters depending on the kind of database the project uses. Supported options include PostgreSQL, MySQL, SQLite, Neon and Supabase, among others (more on this here). Each of them can be connected in many different ways.
I’d like to connect to PostgreSQL running in a Docker container.
Installation:
npm i drizzle-orm postgres
npm i -D drizzle-kit
Initializing the driver:
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { env } from "@/env/server";
import * as schema from "./schema/index";
const queryClient = postgres(env.DATABASE_URL);
const db = drizzle({ client: queryClient, schema });
export default db;
Drizzle configuration (drizzle.config.ts):
import { defineConfig } from "drizzle-kit";
import { env } from "@/env/server";
export default defineConfig({
out: "./src/db/migrations",
schema: "./src/db/schema/index.ts",
dialect: "postgresql",
dbCredentials: {
url: env.DATABASE_URL!,
},
});
Example schema (src/db/articles.ts):
import { relations } from "drizzle-orm";
import {
boolean,
index,
pgTable,
text,
timestamp,
uniqueIndex,
uuid,
varchar,
} from "drizzle-orm/pg-core";
import users from "./users";
const articles = pgTable(
"article",
{
id: uuid().primaryKey().defaultRandom(),
title: varchar("title", { length: 255 }),
slug: varchar("slug", { length: 255 }).notNull(),
content: text("content").notNull(),
image: varchar("image", { length: 2048 }),
isPublic: boolean("is_public").default(false),
authorId: uuid("author_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at", { mode: "string" })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { mode: "string" })
.notNull()
.defaultNow(),
},
(table) => [
uniqueIndex("slug_idx").on(table.slug),
index("title_idx").on(table.title),
]
);
export const articlesRelations = relations(articles, ({ one }) => ({
author: one(users, {
fields: [articles.authorId],
references: [users.id],
}),
}));
The schema is imported in the src/db/schema/index.ts file and wired into the drizzle.config.ts configuration. To query the database, we’ll add a helper function in the src/lib/actions/article.actions.ts file:
"use server";
import db from "@/db";
// ...
export async function getArticleBySlug(slug: string) {
const article = await db.query.articles.findFirst({
where: eq(articles.slug, slug),
});
return article;
}
This method can now be invoked in the page file:
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const article = await getArticleBySlug(slug);
// ...
}
Docker containerization
To run the database in a Docker container, make sure Docker Desktop is installed, as it makes managing containers easy. A Docker container can be started in many ways – straight from the command line or from pre-built images, for example – but let’s take a more structured route. Create a docker-compose.yml file containing all the required information (such as the PostgreSQL image, ports and environment variables):
services:
database:
image: postgres
container_name: readium_postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: readium
ports:
- 5432:5432
volumes:
- dockerreadiumdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d readium"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
volumes:
dockerreadiumdata:
Starting the database then boils down to running one command in the terminal:
docker compose up
Deployment
Deploying and hosting a Next.js application works much like deploying any other application, and a lot depends on the developers’ needs and choices as well as on business decisions.
Next.js can, therefore, be deployed:
- As a Node.js server with any provider that supports this environment
- With any provider that supports Docker containers, including container orchestration like Kubernetes or a cloud provider
- As a static export (for static pages or SPAs)
- Or, finally, adapted to run on various platforms that support the infrastructure
More information is available here.
Summary
In this article, I walked step by step through a modern full stack application architecture built with Next.js 15 and technologies such as TypeScript, Server Actions, Server and Client Components, Auth.js, Tailwind CSS, Drizzle ORM, PostgreSQL and Docker. Beyond showing how these tools fit together, I demonstrated how to set up a clear project structure, handle state and types, and keep the logic cleanly divided between the frontend and the backend.
I hope this knowledge helps you build robust, scalable applications.