0
0
NextJSframework~30 mins

Middleware.ts file convention in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Middleware.ts File Convention in Next.js
📖 Scenario: You are building a Next.js app that needs to run some code before every page loads. This is useful for things like checking if a user is logged in or redirecting them to a special page.
🎯 Goal: Create a middleware.ts file in a Next.js app that runs on every request and redirects users from the homepage to a welcome page.
📋 What You'll Learn
Create a middleware.ts file with the correct export
Use the Next.js NextResponse to handle redirects
Check the request URL pathname to decide when to redirect
Export a config object to specify which paths the middleware runs on
💡 Why This Matters
🌍 Real World
Middleware in Next.js apps helps run code before pages load, like redirects or authentication checks.
💼 Career
Understanding middleware is important for building secure and user-friendly web apps with Next.js.
Progress0 / 4 steps
1
Create the middleware function
Create a file named middleware.ts and write a function called middleware that takes a request parameter.
NextJS
Need a hint?

Start by importing NextResponse from next/server and create the middleware function.

2
Check the request URL pathname
Inside the middleware function, create a variable called pathname that gets the pathname from request.nextUrl.
NextJS
Need a hint?

Use request.nextUrl.pathname to get the current path the user is visiting.

3
Redirect from homepage to /welcome
Inside the middleware function, add an if statement that checks if pathname is exactly "/". If yes, return NextResponse.redirect(new URL('/welcome', request.url)).
NextJS
Need a hint?

Use NextResponse.redirect with a new URL to send users from the homepage to /welcome.

4
Add middleware config for matching paths
After the middleware function, export a constant called config with a matcher array that includes "/" and "/welcome".
NextJS
Need a hint?

The config export tells Next.js which paths to run the middleware on. Use matcher with an array of paths.