
Let's look at Next.js Middleware: Code that runs on the Edge.
Let's look at Next.js Middleware: Code that runs on the Edge.
Next.js Middleware is an awesome feature that allows you to write code over configuration.
Blog Post I wrote about middleware: https://www.jamesperkins.dev/post/usi…
Join this channel to get access to perks:
/ @james-perkins
Want to support the channel? Click below
https://www.buymeacoffee.com/jamesper…
Follow me on:
📃 Website/Blog: https://jamesperkins.dev
👉 Twitter: https://twitter.com/james_r_perkins
👉 Linkedin: https://www.linkedin.com/in/james-per…
👉 Github: https://github.com/perkinsjr
👉 Discord : https://discord.gg/dqYP9Mc
00:00 - Introduction
01:07 - Rewrite the URL
06:42 - Add a cookie
09:30 - Get the user’s geolocation
14:14 - Adding a custom header
16:16 - Outro
Content
0.19 -> What's up, everybody? Welcome back to
the channel and welcome
3.548 -> to this video. In this video, we're
going to be looking
7.028 -> at middleware. Nextjs released
middleware
11.194 -> in the next twelve release as a beta
14.81 -> code has been continuing to improve it
over time.
18.23 -> Now next middleware allows you to use
code over
21.716 -> configuration. So for example, if you
needed to add a
25.784 -> cookie for some reason, you could use
middleware
30.094 -> to do it before the page is actually
accessed
34.222 -> by user and it's on the edge so it's
lightning fast
38.24 -> and the user won't even know that it's
happening. You can
41.804 -> use this for all types of things like
geolocation detection,
46.03 -> adding headers, adding cookies. You
could even
50.012 -> test to make sure if your site is in
maintenance mode. Maybe you do maintenance
54.262 -> on a Monday. So we're going to be
looking at middleware and
57.872 -> doing a few examples so that you can
understand how middleware
61.498 -> is used with next year's. So let's
start digging in to
64.892 -> some code. So here we are inside a
NextJS project. This is
69.032 -> completely standard from Create next
app. And what we're going
72.344 -> to do is start with a very simple
example of checking
76.354 -> to see if today is Monday and if it
is,
80.024 -> our site is going to be in maintenance
mode. So we're going to redirect the
83.564 -> user to the maintenance URL. So the
first
87.584 -> thing we need to do is really create a
new page folder here and we'll
90.586 -> call it maintenance.
93.71 -> And inside this maintenance folder
here we're going to create a new file.
97.294 -> I'm just going to call it index. Js.
And inside of here we'll
101.374 -> just copy our index page. So we get
all the styles
106.01 -> and just add an extra dot so
111.684 -> that our styles can be inserted. And
then instead
116.076 -> of all of this we'll just have a nice
120.3 -> simple main and
124.368 -> then the returning Div and
128.148 -> we can hit save here. And now what
we're going to do
132.144 -> is we're going to use next year's
middleware to
136.104 -> basically redirect someone here if
they happen to fall
140.652 -> on a Monday. So what we can do here is
say welcome to
144.456 -> our maintenance page,
147.63 -> sorry, no transactions
151.814 -> today. Now if we navigate to that site
155.46 -> and that web page, it will pull up the
maintenance page.
158.472 -> But what we want to do is implement
middleware on
161.88 -> every route. So to do that we would do
it in the route
166.022 -> in the James on the root of that and
we just do
169.404 -> underscore middleware. Js. Now this
will run
173.208 -> every single time someone navigates to
any page.
176.58 -> We can do that. We're going to import
next response.
180.93 -> Now, next response essentially holds
what is coming
184.356 -> from next and we can look inside of
that for all
187.764 -> sorts of things in our request and
then send the response
191.93 -> back to the user. So next response
essentially says hey,
195.396 -> let's rewrite this URL and we can send
that down
198.684 -> to the user or next response. Let's
add a cookie or something
203.076 -> similar. So now we have next response.
We can just do a normal
207.554 -> function here that's asynchronous and
we'll call it middleware.
211.01 -> You can call it whatever you want but
I would advise calling it middleware
215.198 -> because that seems to be best
practices at this point.
218.79 -> So now we have that we can do Const
URL
223.17 -> requestnexturl clone.
227.31 -> So this gives us a clone of the next
URL. So that would be like
231.108 -> slash or about or whatever your
234.576 -> URL is and then we can start playing
around with it. So to
238.104 -> make this really simple I didn't want
to do some sort of like random or
242.448 -> maybe some sort of calculation to see
how many requests have been before
246.072 -> we show maintenance mode. But this
will give you an idea.
250.02 -> So we've got a date now and we're just
going to say can't stay equals
255.254 -> date getday
259.81 -> and inside that get day we're going to
do a check and
263.416 -> we're going to say is maintenance and
267.604 -> we'll say equals day equals equals
271.734 -> one because Monday is day one and
Sunday is day
275.5 -> zero. We can then say if is
281.35 -> maintenance URL
285.742 -> path name. So we're going to set the
URL path name equal
289.366 -> to whatever you want. So in this
example we
293.036 -> want to set it to slashmaintenance so
maintenance and
298.364 -> then underneath that we can also do
console
302.098 -> log site is down
306.95 -> and we'll be able to see that on the
server. And then all we have
310.016 -> to do now is do the return so we can
do returnnextresponse
315.05 -> rewrite. So we're telling we want to
rewrite the URL
319.09 -> from the original URL to this new one
that we've
322.546 -> just set up. So that's everything
326.024 -> to do with a basic maintenance. So now
if
329.636 -> it is a maintenance we'll go ahead and
shove them into this
333.212 -> URL that we just created. Otherwise
they'll just get the home page.
336.848 -> So if we run you on Dev now and we
launch our
340.664 -> website, we should see that change. So
here we are on Google
344.36 -> Chrome and I'm going to type in
localhost 3000 and
347.984 -> it says welcome to our maintenance
page. Sorry, no transactions today.
352.34 -> Then if I go back to the code that we
were just in and change
355.172 -> this to day three which would be
Wednesday and we
358.316 -> go back to our page and you now see
that we get our normal
361.558 -> NextJS page. So that's a way to check
to
364.952 -> see if something is true and
redirecting the user back
368.852 -> to another page versus having to do
this either on
372.116 -> the server side in SSR or in client
side after
376.04 -> the fact. Now we've covered a basic
maintenance. What if we wanted
380.468 -> to add a cookie to our page? Well we
can do
384.404 -> that as well. So I'm going to create a
new folder here we're going to
387.056 -> call it cookies and inside that folder
we're going to create an index
390.562 -> JS that's going to hold our page that
we're going
393.824 -> to view. And now I'm only going to run
this on
398.084 -> this page itself. So if you put the
middleware inside of a
401.624 -> folder like this, it will only run if
someone navigates
405.118 -> to this site. So our middleware for
this one is
409.484 -> going to be just as simple as the last
one it's set
413.264 -> from. We're just going to add a cookie
to the response. So to
417.104 -> do that we can import next response
425.49 -> and that's going to come from next
SaaS server
431.01 -> and then we're going to do the same
export function middleware.
436.17 -> In this case, we don't actually need
it to be asynchronous. We can just
439.884 -> do Const response and then
452.992 -> say So this is basically getting the
response and
456.304 -> saying we want to add something to the
response before you send it down.
459.352 -> So we can do response cookie and then
inside
462.94 -> of here we can give it a cookie name.
So let's say dark mode and
466.024 -> then comma true and then
470.212 -> we can do the response. So return
response.
477.25 -> So that's it for adding a cookie. You
can add it at any time.
480.616 -> Obviously if you had some more logic
like you had to go and check or
484.036 -> you have to go to a server, something
like that, you'd want to make an
486.544 -> asynchronous function. But the idea is
the same. We're basically telling it,
490.444 -> hey, we want to add a cookie to our
response and now we
493.756 -> can actually access that. So let's
look at another
497.296 -> index. Js where we put in something
here.
501.196 -> So I'm going to grab our maintenance
page here
505.51 -> and we'll paste it in here and
509.392 -> say check for your cookies, check for
a
512.68 -> cookie. It's a nice surprise
517.75 -> and that's it. So now we can go and
check that and see how that
521.14 -> works as well. So we're back in our
site here, we can go to SaaS
524.538 -> cookies and it says check for a
cookie. It's a
528.016 -> nice surprise. Now if we go here and
look at our local host
532.194 -> and I'll Zoom in a bit more, you can
see we've added this cookie called
535.24 -> Dark mode and it's set to true. Now
we've tried
539.5 -> adding a cookie. We've also done our
maintenance mode. What if
543.184 -> we checked where someone is located?
So for this example,
546.82 -> we're going to do a couple of
different things. First, in our
550.06 -> index page that we're going to write
for this section,
553.062 -> we're actually going to try and look
for the geolocation in
556.612 -> two different areas. So I can show you
how that works. So you can
559.852 -> access it in two different spots. And
of course we'll test to
563.236 -> make sure our code works. So we'll
create
566.512 -> a new folder here called geolocation.
And inside
570.46 -> of here we'll create an index JS and
574.06 -> an underscore middleware.
577.15 -> Js. Now inside of here we can actually
run this
581.236 -> and check to see if someone is located
somewhere.
585.282 -> So inside of our middleware here for
just geolocation,
589.662 -> we can again import the same thing.
And as you can see, we don't require
594.054 -> any other packages to do this work.
It's just available and
598.204 -> when it's not available we can set a
default
601.746 -> so that we don't break our
application. So again
605.272 -> export async function middleware
610.27 -> request then we can say Const
614.17 -> and we're going to do two different
things here. I'm going to ask for the
616.924 -> next URL and I'm going to call it URL
and then
620.248 -> we're going to get the geo from the
request.
623.59 -> Then we can say console log, let's say
geo
628.17 -> country and we'll log that out
631.756 -> to our console so we can see it and
then we can say Const country
635.836 -> equals geo country and
642.224 -> then if we don't for some reason have
access we'll just set it to the
645.116 -> US so that we don't break it. Then
we're going to URL searchparams
650.87 -> set country.
655.652 -> So we're going to set the country to
that and then all we have to
658.736 -> do now is return our response again.
So we're going to do
661.904 -> next response, rewrite URL.
667.462 -> So we're going to rewrite the URL back
to this geocountry.
672.01 -> So now we have that in our middleware.
Now we actually need to do
675.14 -> our index JS. So first let's just copy
a different one.
678.848 -> But there's going to be some extra
code here that we need to insert
682.042 -> in. So what we're going to
685.604 -> do here is we're going to add a use
router
689.362 -> because you can actually access this
in the US router if you needed it
692.816 -> for some reason. So userouter from
next slashrouter
698.33 -> and we can say we want to access this
on the server
701.986 -> side beforehand. So we can say export
Const get
705.752 -> serversideprops.
709.73 -> Then we'll pass in a query and then
we'll
713.614 -> return props dot query and
718.604 -> that's it. That's all we're going to
do here. So basically we're going to
721.904 -> take the query in here from server
side props and we're just going to return
724.976 -> it as props query
729.89 -> and that's it. And that should give us
what we need to
733.304 -> make this work. So now we have our
getserver side props and we got this
736.604 -> props query. We can obviously pass our
props along and
741.164 -> then we can use it however we want. So
we can do console logprops
747.47 -> country. So we will access
750.836 -> that from our SSR
755.038 -> here. But we can also do
760.13 -> constrouter equals userouter
764.758 -> which is the standard way to use
router and then
768.392 -> console log router query.
772.558 -> So we have two options here. So let's
say you needed it for your server
776.146 -> side props rate. This is kind of an
example I'm trying to produce here.
779.624 -> Maybe we need to know the location so
maybe we get
783.416 -> parity pricing or something like that.
786.632 -> You can use it by just passing in the
query and the query will be
790.064 -> part of that option. So we could use
like query country
797.99 -> and then some sort of logic there or
801.752 -> you can actually access it directly
through the router. Let's save this and
805.424 -> we'll say hello from
810.59 -> props country.
815.25 -> So let's go ahead and launch and see
what that looks like. So as you
818.388 -> can see it says hello from the US. But
the problem is I'm on local
821.58 -> host so it's just going to return
whatever country I'm in.
824.652 -> So what I've done is I've launched
chefshark VPN and I'm now
828.792 -> in the UK but I also need to deploy
this so I've done that
832.728 -> and let's go ahead and test it out. So
let's go ahead and I've deployed
836.246 -> it. Now let's check it. We should be
in GB so
839.484 -> there we go. And as you can see,
welcome to
843.18 -> GB or welcome to great Britain. So
let's do
846.816 -> one more where we add a header before
the user hits the
850.524 -> page. So the last one we're going to
do is adding a header. So I'm
853.598 -> going to create another folder here
and we'll call it add header.
857.894 -> We'll do a new index. Js file and a
middleware
861.998 -> and I'm obviously keeping these
separated to make it easier to
865.56 -> grasp the concepts. But you could do
this all in one file. If you really
869.052 -> needed to add a header and a cookie
and detect the geolocation,
872.726 -> et cetera, et cetera, all those things
are possible on the edge.
877.35 -> So for the middleware here we're going
to be basically adding a
881.172 -> header to the response so we can do
that by importing next response
885.866 -> again from nextserver
891.99 -> and we do export function or export
895.706 -> async function middleware
902.59 -> request. So now we have the request we
can do
906.04 -> response so response equals
909.738 -> next response NextJS. So that will be
the
913.492 -> next response. Then all we need to do
is grab
916.914 -> the headers so we can do headers set
and
921.064 -> now we can set a header as we see fit.
So I'm going to add
924.364 -> a custom one here. X James header
hello
930.256 -> from the edge and then we just need to
return
933.856 -> the response. So return response and
hit save.
938.05 -> So now we have our response here and
what
941.836 -> I've done is taken the cookie code and
just added
945.414 -> check your header for a surprise. So
we're back
948.7 -> in the application, we can do add
header here and it says check your
952.384 -> headers for a surprise. And if we open
up our
956.95 -> console here and hit the
960.124 -> refresh and go to our add header
section
964.014 -> here and go to headers and scroll
down.
967.87 -> If I Zoom in a bit more you can see X
James header
972.054 -> hello from the edge.
975.43 -> So there you have it. Next middleware.
The future of edge functions
979.698 -> before a page has even loaded. If you
did enjoy this
983.032 -> video, make sure to drop it a like
subscribe to more content.
986.26 -> Ten we're live Mondays, Tuesdays,
Wednesdays and Thursdays on the
990.184 -> channel around 230 Eastern. And of
993.976 -> course, I'll see you in the next
video.
Source: https://www.youtube.com/watch?v=Kd_Ob-13mXE