Language:

Search

Nextjs Middleware and Edge functions

  • Share this:
Nextjs Middleware and Edge functions

 

Middleware is still in beta version so there would be some bug issues out there

There has been many new features and optimisations but in this blog we will focus on new beta release of Nextjs middleware and Edge functions.

Also Read: Mean stack Interview questions

Edge Functions

If you ever had experience with Serverless functions this would feel familiar.

Before coming to explain edge functions let's discuss first how nextjs works at the moment. There are two type of pages one with static content and other with dynamic.

Static content are rendered fast because it's served from CDN. The downside of CDN are that our content is not personalised and dynamic.

Dynamic content on other hand is more personalised but its not fast because the content needs to be queried from remote server. If server is in US and request is made from asian countries then it might take time to fetch the data and render the page.

Edge functions solves this problem, Its fast as CDN with dynamic pages. Edge functions sits between user and origin server. Unlike regular server, edge functions runs closer to the user for best performance.

The next feature that was released along edge functions was middleware. They run on edge functions that would mean it will take full advantage.

Also Read: Static Generation in NextJS

Middleware

The concept of middleware is not new its been there on Backend as well as Frontend. Nextjs introduced middleware that would run on edge function.

Middleware would run before every request that has been made on nextjs. So if the user request any page or any api route the middleware logic would run right before the request. This would solves problem of sharing the common login across the application like Authentication, Bot protection, Redirects, Browser support, Feature flags, A/B Testing, ServerSide analytics, Logging.

Middleware runs on runtime v8. That would mean we can use web apis like fetch etc. With middleware we can Rewrite, Redirect, Add headers, Stream html.

It runs out of the box on applications that are hosted on vercel but can also works on other servers using next start

To get started with middleware you would need to create a file _middleware.js or _middleware.ts under pages or api. The best thing about middleware is that it can be scoped to limited routes. For example if we have to add middleware for blog/[id] scope then _middleware file needs to be created under blog folder.

Let's share some of the use cases of middleware.

//Middleware that block the content for specific country.

export function middleware(req: NextRequest) {
  const country = req.geo.country || 'UK'

  if (country === 'US) {
    return new Response('Blocked for Geo fencing reasons', { status: 451 })
  }
  return new Response(`Greetings from ${country}, where you are not blocked.`)
}
//Middleware that Rewrites the url along with country and city of user

export async function middleware(req: NextRequest) {
  const { nextUrl: url, geo } = req
  const country = geo.country || 'US'
  const city = geo.city || 'San Francisco'

  url.searchParams.set('country', country)
  url.searchParams.set('city', city)

  return NextResponse.rewrite(url)
}

Conclusion

Middleware is Next-Gen feature and it has a lot of utility in modern applications. It will solves basic problems like Authentications, Geolocations etc very efficiently. With the help of Edge function the middleware would run faster like Static web applications. Keep in mind that Middleware is still in beta version so there would be some bug issues out there.

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques