EthicsComputerCourses
Join training +91 90532 10052

Set Up a Full Stack Next.js Project

Next.js Full Stack · Lesson 2 of 20 Intermediate 13 min read Updated

By the end of this lesson you will have the EventHub project on your computer: created with create-next-app, running in the browser, building for production and saved in Git. You will also set up the environment files and scripts that every later lesson relies on, so secrets never reach Git or the browser.

What you should know first: What Is Full Stack Next.js? and how to open a terminal. The Next.js course explains every create-next-app question in Create a Next.js App; this lesson makes the choices for a full stack app and goes further. If Node.js or Git is new to you, see Install Node.js and Install & Configure Git.

What you need

Think of a cricket team before a match: kit checked, pitch inspected, scorebook ready. A missing glove found during the first over costs more than one found in the dressing room. Check your tools now.

ToolVersion checked on 16 Nov 2026Why EventHub needs it
Node.js20.9 or newer (26 LTS recommended)Runs Next.js, Prisma and every build tool
npmcomes with Node.jsInstalls packages
Next.js16.4.6 (latest on npm)The framework
React19.3The UI library inside Next.js
Gitany recent versionSaves versions; keeps secrets out with .gitignore
PostgreSQL18, or Prisma's local dev databaseThe database, from the Prisma lesson onwards
VS Code or another editorlatestWriting TypeScript with good hints

You do not need PostgreSQL today. Database with Prisma & PostgreSQL shows two ways to get one, including a local database that needs no installer. If you want to install the real server now, follow Install PostgreSQL.

Step 1: Check Node.js and npm

Terminal
node -v
npm -v
Output
v22.14.0
10.9.2

That is the computer used to test this course. Next.js 16 needs Node.js 20.9 or newer, so any 22.x, 24.x or 26.x release works. On a fresh install of the current LTS you will see a v26 number. If you see v18, upgrade before going on, because Next.js 16 does not support it.

Step 2: Create the app

Go to the folder where you keep projects and run:

Terminal
npx create-next-app@latest eventhub --yes

--yes accepts the recommended defaults without asking questions: TypeScript, ESLint, Tailwind CSS, the App Router, no src/ folder, the @/* import alias and Cache Components. Those are exactly the choices this course uses. Here is the real output, with the long package lists shortened:

Output
Creating a new Next.js app in C:\Users\meera\code\eventhub.

Using npm.

Initializing project with template: app-tw

Installing dependencies:
- next
- react
- react-dom

Installing devDependencies:
- @tailwindcss/turbopack
- @types/node
- @types/react
- @types/react-dom
- eslint
- eslint-config-next
- tailwindcss
- typescript

added 359 packages, and audited 360 packages in 14m

8 moderate severity vulnerabilities

Generating route types...
✓ Types generated successfully

Initialized a git repository.

Success! Created eventhub at C:\Users\meera\code\eventhub

Fourteen minutes is slow: the test machine was busy, and on a normal connection it takes one or two. Two lines deserve attention:

  • "8 moderate severity vulnerabilities" comes from npm audit, which checks every package against a list of known problems. Most reports in a fresh project are in development tools, not in code that runs on your server. Do not run npm audit fix --force blindly; it can install breaking major versions. Read npm audit, and keep next itself up to date, because Next.js releases carry security fixes.
  • "Generating route types" creates the PageProps and LayoutProps types you will use in App Router Structure.

create-next-app also made the first Git commit for you.

Step 3: Look at what you got

Text
eventhub/
├── app/
│   ├── favicon.ico
│   ├── globals.css
│   ├── layout.tsx
│   └── page.tsx
├── public/              file.svg, globe.svg, next.svg, vercel.svg, window.svg
├── .gitignore
├── AGENTS.md
├── README.md
├── eslint.config.mjs
├── next-env.d.ts
├── next.config.ts
├── package.json
├── package-lock.json
└── tsconfig.json

AGENTS.md is a short note for AI coding assistants, telling them to read the Next.js docs that ship inside node_modules/next/dist/docs/ for your exact version. Keep it; it is harmless. The interesting file is next.config.ts:

TypeScript
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* config options here */
  cacheComponents: true,
  partialPrefetching: true,
  turbopack: {
    rules: {
      "*.css": {
        loaders: ["@tailwindcss/turbopack"],
        as: "*.css",
      },
    },
  },
};

export default nextConfig;

cacheComponents: true switches on the Next.js 16 caching model: data is fresh on every request unless you opt in to caching with "use cache". It also asks you to wrap request-time data in <Suspense>, which you will meet in Server Components & Data Fetching. partialPrefetching lets links prefetch the static parts of a page. The turbopack rule runs Tailwind CSS on your CSS files. The details are in the Next.js course's Caching with use cache lesson.

Step 4: Run the development server

Terminal
cd eventhub
npm run dev
Output
▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3123
- Network:       http://192.168.1.12:3123
✓ Ready in 3.1s
✓ Running next.config.ts took 253ms
- Cache Components enabled
- Partial Prefetching enabled

○ Compiling / ...
 GET / 200 in 3.7s (next.js: 2.3s, application-code: 1378ms)

Your address will be http://localhost:3000. Our test machine already had another app on port 3000, so we started this one with npm run dev -- -p 3123. The last line appeared when the browser opened the page: a GET request, status 200 and the time it took. Watching these lines is the quickest way to see what your server is doing. Stop the server with Ctrl + C.

The Network address lets a phone on the same Wi-Fi open your app, which is handy for testing on mobile. Never expose the development server to the internet; it is not built for that.

Step 5: Plan environment variables

An environment variable is a named setting, such as a database address, given to the program from outside the code. Secrets belong there, never in source files. Think of the locker key at a railway station cloakroom: the cloakroom (your code) is public, the key (the secret) stays in your pocket.

EventHub keeps its settings in one file named .env in the project root. Next.js reads .env automatically, and the Prisma command-line tool will read the same file, so you never keep two copies. This table fixes the names for the whole course:

NameAdded inWhat it holds
DATABASE_URLDatabase with Prisma & PostgreSQLThe PostgreSQL connection string
AUTH_SECRETAuthentication with Auth.jsA long random string that signs login sessions

Later lessons add their own names to the same file. None of them starts with NEXT_PUBLIC_, because that prefix copies the value into browser JavaScript. Use it only for values that are fine to publish, such as a public site URL.

Now a trap in the generated .gitignore. It contains this line:

Text
# env files (can opt-in for committing if needed)
.env*

That ignores .env, which is good, but also .env.example, which you want to commit. An example env file lists every variable name with a harmless placeholder, so a teammate knows what to fill in. Add an exception below that line:

Text
.env*
!.env.example

Then create .env.example:

Terminal
# Copy this file to .env and fill in real values. Never commit .env.
DATABASE_URL="postgresql://eventhub_app:change-me@localhost:5432/eventhub"

The value is a placeholder showing the format, not a real password. The user name eventhub_app is a hint for later: the app connects as its own database user with only the rights it needs, never as the postgres superuser.

Step 6: Helper packages and scripts

Install one small package now:

Terminal
npm install server-only

server-only does nothing at run time. Its job is to make the build fail if a file that imports it ends up in browser code. Every data file in EventHub starts with import "server-only";.

Next, open package.json and add a typecheck script and an engines field. The four scripts from create-next-app stay as they are:

JSON
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint",
    "typecheck": "next typegen && tsc --noEmit"
  },
  "engines": {
    "node": ">=20.9"
  }
}

next typegen writes the route types without a full build, and tsc --noEmit checks every file without producing output. It is much faster than a build, so run it before each commit. engines documents the minimum Node.js version for your team, and some hosting platforms, such as Vercel, read it to choose a Node.js version.

Terminal
npm run typecheck
Output
> eventhub@0.1.0 typecheck
> next typegen && tsc --noEmit

Generating route types...
✓ Types generated successfully

tsc prints nothing when there are no errors. Silence is success here.

Step 7: Build once, then commit

Before writing any feature, prove the production build works:

Terminal
npm run build
Output
▲ Next.js 16.4.6 (Turbopack)
✓ Running next.config.ts took 329ms
- Cache Components enabled
- Partial Prefetching enabled

  Creating an optimized production build ...
✓ Compiled successfully in 24.5s
  Running TypeScript ...
  Finished TypeScript in 21.5s ...
  Collecting page data using 5 workers ...
✓ Generating static pages using 5 workers (4/4) in 14.5s
  Finalizing page optimization ...

Route (app)
┌ ○ /
└ ○ /_not-found


○  (Static)  prerendered as static content

Both routes are static (○): nothing in the starter page reads data at request time. You will watch this table change as EventHub grows. Since Next.js 16, next build no longer runs the linter, so run npm run lint yourself too.

Finally, save your work:

Terminal
git status --short
git add .
git commit -m "Set up EventHub: env example, server-only, typecheck script"
Output
 M .gitignore
 M package-lock.json
 M package.json
?? .env.example
[main 0a18a60] Set up EventHub: env example, server-only, typecheck script
 4 files changed, 2290 insertions(+), 53 deletions(-)
 create mode 100644 .env.example

M means modified and ?? means a new file Git is not tracking yet. Your commit id and line counts will differ (ours also included the Prisma packages from a later lesson). On Windows, Git may add harmless "LF will be replaced by CRLF" warnings.

Check that .env.example is in the list and .env is not. If .env ever appears in git status, stop and fix .gitignore before committing.

Try it: which variables reach the browser?

This small tool reads the text of an env file and reports which values Next.js would copy into browser code. Edit the text in the code and run it again:

React JSXOpen in editor
import { createRoot } from "react-dom/client";

const envFile = `
DATABASE_URL="postgresql://eventhub_app:s3cret@localhost:5432/eventhub"
AUTH_SECRET="k9f2...long-random..."
NEXT_PUBLIC_SITE_URL="https://eventhub.example.in"
NEXT_PUBLIC_RAZORPAY_SECRET="oops"
`;

const risky = /SECRET|PASSWORD|DATABASE|PRIVATE|TOKEN/;

const rows = envFile
  .split("\n")
  .map((line) => line.trim())
  .filter((line) => line && !line.startsWith("#"))
  .map((line) => {
    const name = line.slice(0, line.indexOf("="));
    const isPublic = name.startsWith("NEXT_PUBLIC_");
    return { name, isPublic, warn: isPublic && risky.test(name) };
  });

rows.forEach((r) => {
  const where = r.isPublic ? "sent to the browser" : "server only";
  console.log(`${r.name} -> ${where}${r.warn ? " (WARNING: looks secret)" : ""}`);
});

function Report() {
  return (
    <ul>
      {rows.map((r) => (
        <li key={r.name} style={{ color: r.warn ? "crimson" : "inherit" }}>
          <code>{r.name}</code>: {r.isPublic ? "sent to the browser" : "server only"}
        </li>
      ))}
    </ul>
  );
}

createRoot(document.getElementById("root")).render(<Report />);
Output
DATABASE_URL -> server only
AUTH_SECRET -> server only
NEXT_PUBLIC_SITE_URL -> sent to the browser
NEXT_PUBLIC_RAZORPAY_SECRET -> sent to the browser (WARNING: looks secret)

The last line is the classic mistake: someone adds NEXT_PUBLIC_ to "make it work" in a Client Component, and the payment secret is now in every visitor's browser. Secrets must be used only in server code. The full rules are in Environment Variables.

Common mistakes

  • Committing .env. If a secret ever reaches Git, removing the file is not enough: the old commit still has it. Change (rotate) the secret at once.
  • Ignoring .env.example by accident. The generated .env* rule hides it; add !.env.example.
  • Using NEXT_PUBLIC_ for a secret. The value is copied into JavaScript files that anyone can download.
  • Running npm audit fix --force on day one. It may upgrade packages across breaking versions. Read the report first.
  • Testing only with npm run dev. Some behaviour, such as static prerendering, appears only after npm run build.

Interview questions

1. What does create-next-app --yes choose for a new project in Next.js 16.4?

The recommended defaults: TypeScript, ESLint, Tailwind CSS, the App Router, no src/ folder, the @/* import alias and Cache Components, with Turbopack as the bundler. It also installs dependencies, generates route types and makes an initial Git commit.

2. Why keep an .env.example file in the repository?

It documents every environment variable the app needs, with harmless placeholder values, so a new developer or a deployment platform knows what to set. The real .env with secrets stays out of Git.

3. What is the difference between DATABASE_URL and NEXT_PUBLIC_DATABASE_URL in Next.js?

DATABASE_URL is available only to server code. Any variable starting with NEXT_PUBLIC_ is inlined into the browser bundle at build time, so it becomes public. A database URL must never have that prefix.

4. What does the server-only package do?

When a module imports server-only, the build fails if that module is pulled into a Client Component. It turns an accidental leak of server code or secrets into a build error that you see before deploying.

Key points

  • Next.js 16 needs Node.js 20.9 or newer; this course was tested with Next.js 16.4.6 and React 19.3.
  • npx create-next-app@latest eventhub --yes gives TypeScript, Tailwind, ESLint, the App Router and Cache Components.
  • EventHub keeps settings in .env (git-ignored) and documents them in a committed .env.example.
  • Never give a secret the NEXT_PUBLIC_ prefix.
  • server-only, npm run typecheck and npm run lint catch problems before the build does.
  • Build once at the start, read the route table, and commit.

Exercise

Rohan cloned your EventHub repository on his laptop in Lucknow. Write the exact steps he follows to get it running, from git clone to seeing the page in his browser. Include how he finds out which environment variables to set, and one check that proves his .env will not be committed.

Show solution
Terminal
git clone https://github.com/your-name/eventhub.git
cd eventhub
node -v                # must be 20.9 or newer
npm install            # installs exact versions from package-lock.json
cp .env.example .env   # then edit .env with his own values
git check-ignore -v .env
npm run dev

.env.example tells him which names to fill in. git check-ignore -v .env prints the .gitignore rule that matches, such as .gitignore:34:.env* .env, which proves Git will not track the file. On Windows PowerShell he can use Copy-Item .env.example .env instead of cp.

Quick Quiz

1. Which Node.js version is too old for Next.js 16?

2. Why does EventHub add !.env.example to .gitignore?

3. What does cacheComponents: true in next.config.ts mean?

4. Which command checks types without building the app?

Learn Next.js Full Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call