<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Justin Jaeger on Medium]]></title>
        <description><![CDATA[Stories by Justin Jaeger on Medium]]></description>
        <link>https://medium.com/@justinjaeger?source=rss-fd0bc27f5dde------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s4q0HsU2z-RR90v3rqPUTQ.png</url>
            <title>Stories by Justin Jaeger on Medium</title>
            <link>https://medium.com/@justinjaeger?source=rss-fd0bc27f5dde------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:52:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justinjaeger/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Next.js — Using Cookies in getServerSideProps]]></title>
            <link>https://javascript.plainenglish.io/next-js-using-cookies-in-getserversideprops-89c03a216b0b?source=rss-fd0bc27f5dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c03a216b0b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Justin Jaeger]]></dc:creator>
            <pubDate>Tue, 16 Mar 2021 16:51:13 GMT</pubDate>
            <atom:updated>2021-03-17T08:59:43.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*LQP0NWfKVKj4ZrGDiOS9sA.png" /></figure><h3>Next.js — Handling Cookies in <strong>getServerSideProps</strong></h3><p>As I ventured to build an authentication workflow in Next.js, I found myself struggling to handle cookies in <strong>getServerSideProps.</strong></p><h3>The Problem</h3><p>I want to fetch my user’s data on the server before rendering the page, meaning I’ll first need to validate the access token, which is encrypted in a browser cookie. I want the ability to update, delete, and set multiple new cookies before rendering a page.</p><p>Because I need to reuse the functionality for validating the user token, I need the ability to handle cookies in designated functions outside the scope of my getServerSideProps function. For example, making a request to my API from inside getServerSideProps. <strong>This is where things get tricky.</strong></p><p>In attempting these cookie operations, I quickly realized:</p><blockquote>It matters whether you are calling your cookie handling functions from getServerSideProps or normal API endpoints.</blockquote><p>I found that when testing my validation endpoints via Postman, the cookies were setting just fine. But when I loaded a page from<strong> </strong>getServerSideProps, they were not setting in the browser</p><p>Why is this the case?</p><p>You don’t call getServerSideProps <strong>from the browser</strong> like you would an API route, therefore you cannot set cookies in the browser using the same methods. We have to work with Next.js’s <a href="https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#context-object"><strong>context object</strong></a> rather than Node’s request object. We’ll do this with the help of libraries. But the libraries won’t provide us with an integrated approach for<em> passing cookies from functions to getServerSideProps</em></p><p>Let me explain how I handle cookies in a <em>normal</em> API request before we get into server rendering.</p><h3>Reading/Writing cookies from the client</h3><p>I decided to mimic the eases of Express’s cookie handling and add a res.cookie function on my response object. The reason for doing so is that when working in vanilla Node.js, we have to set cookies via:</p><pre>res.setHeader(“set-cookie”, value)</pre><p>and as the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie">documentation states</a>:</p><blockquote>To send multiple cookies, multiple <strong>Set-Cookie</strong> headers should be sent in the same response.</blockquote><p>In other words, you cannot call res.setHeader multiple times and expect the final header to contain all of your cookies. It will only set the header to the last value you passed.</p><p>What you have to do instead is pass an <strong>array </strong>of <strong>serialized cookies </strong>to the header<strong>.</strong></p><h4>Here’s the blueprint:</h4><p>I want to have a simple, express-like<strong> res.cookie</strong> function that adds a cookie to an array, then be able to call a function, <strong>res.sendCookies</strong>, to actually write the array of cookies to the header.</p><h4>Using a wrapper</h4><p>We can add any functions we want to the native req and res objects by exporting our functions inside of a wrapper. This is how we’ll use res.cookie.</p><p>Here’s what your serverless functions will look like with a wrapper:</p><pre>import wrapper from &#39;utils/wrapper&#39;;</pre><pre>const handler = async (req, res, next) =&gt; {<br>    // code and such<br>};</pre><pre>export default wrapper(handler);</pre><p>And this is a peek inside of the wrapper:</p><pre>  import cookie from ‘utils/cookies’;</pre><pre>  const wrapper = handler =&gt; {</pre><pre>    return (req, res, next) =&gt; {</pre><pre>       res.cookieArray = [];</pre><pre>       res.cookie = (name, value, options) =&gt; {<br>         cookie(res, name, value, options);<br>       };</pre><pre>       res.sendCookies = () =&gt; {<br>         res.setHeader(&#39;set-cookie&#39;, res.cookieArray);<br>       };</pre><pre>       return handler(req, res, next);</pre><pre>    };<br>  };</pre><h4>res.cookie()</h4><p>This function sets or deletes a cookie, depending on whether the <strong>value</strong> argument is empty, by serializing it and pushing it to our res.cookieArray.</p><pre>import { serialize } from ‘cookie’;</pre><pre>const cookie = (res, name, value, options) =&gt; {<br>  if (!options) options = {};<br>  options.path = ‘/’;<br>  const stringValue = (typeof value === ‘object’)<br>      ? ‘j:’ + JSON.stringify(value) <br>      : String(value)</pre><pre>if (‘maxAge’ in options) {<br>    options.expires = new Date(Date.now() + options.maxAge);<br>    options.maxAge /= 1000;<br>  };<br>  if (!value) {<br>    options.expires = new Date(Date.now() — 1000);<br>  };</pre><pre><strong>// if we pass a value, it sets the cookie<br></strong>  if (value) {<br>    res.cookieArray.push(<strong>serialize</strong>(name, String(stringValue), options))</pre><pre><strong>// if we do not pass an empty string as a value, it deletes the cookie<br></strong>  } else {<br>    res.cookieArray.push(<strong>serialize</strong>(name, ‘’, options))<br>  };</pre><pre>}</pre><pre>export default cookie;</pre><p>With this code, you should be able to handle writing and deleting cookies when you call your API directly from the browser or Postman.</p><p>Now, onto handling cookies in getServerSideProps.</p><h3><em>Reading</em> cookies from the server</h3><p>This is fairly simple. It is sufficient to rely on external libraries that parse Next.js’s context object for this job rather than attempt it yourself. I use <a href="https://www.npmjs.com/package/next-cookies">next-cookies</a> to <strong>get </strong>cookies on the server:</p><pre>import cookies from ‘next-cookies’;</pre><pre>const c = cookies(context);</pre><pre>const myAuthenticationCookie = c.authenticationToken;</pre><p>Now for the trickier part:</p><h3>Writing cookies from the server</h3><p>We’ve already laid the groundwork in how we handle our cookies in our controller functions and API endpoints by adding a <strong>res.cookies</strong> method and a <strong>res.cookieArray</strong>.</p><p>Consider my scenario from the beginning. I make a fetch request to an endpoint on my API <strong>from</strong> getServerSideProps. When it returns a response, I won’t have access to the res object that I’ve been using all of this time to accumulate my cookies. So I simply have to return the cookieArray in my response.</p><pre>return res.json({<br>  otherData: data,<br>  cookieArray: res.cookieArray<br>});</pre><p>Then, in getServerSideProps, I need to parse this cookieArray and write each cookie onto the <strong>context</strong> object. I created a function that is invoked like this:</p><pre>parseCookies(res.data.cookieArray, context);</pre><p>Note that <strong>context </strong>is Node.js’s native object, originating from here:</p><pre>export async function getServerSideProps(<strong>context</strong>) {};</pre><p>Finally, here is my parseCookies function. To do the heavy lifting of writing to the context object, I am relying on <a href="https://www.npmjs.com/package/next-cookie">next-cookie</a> (as opposed to <strong>next-cookies</strong>).</p><pre>import { useCookie } from &#39;next-cookie&#39;;</pre><pre>function parseCookies(array, context) {<br>  const cookie = useCookie(context);<br>    for (let string of array) {<br>      const arr = string.split(&#39;;&#39;)</pre><pre>      const options = {};<br>      const key = arr[0].split(&#39;=&#39;)[0];<br>      const value = arr[0].split(&#39;=&#39;)[1];</pre><pre>      arr.shift();<br>      for (let option of arr) {<br>        let key = option.split(&#39;=&#39;)[0].slice(1);<br>        let value = option.split(&#39;=&#39;)[1];</pre><pre>        if (key === &#39;Path&#39;) key=&#39;path&#39;<br>        else if (key === &#39;Expires&#39;) key=&#39;expires&#39;<br>        else if (key === &#39;HttpOnly&#39;) key=&#39;httpOnly&#39;, value=true;<br>        options[key] = value;<br>      };</pre><pre>    if (value !== &#39;&#39;) cookie.set(key, value, options)<br>    else cookie.remove(key);<br>  };<br>};</pre><pre>export default parseCookies;</pre><p>Essentially, this parses the serialized cookie strings that I passed into cookieArray and either sets or deletes each one using the function imported from next-cookie.</p><h3>Improving your Next.js serverless framework</h3><p>I am striving to get the most out of Next.js’s API and use an Express-like framework so I can leave my backend logic to controllers rather than stuffing everything in Next.js’s serverless functions. If you’re trying to achieve a similar result, check out my article on <a href="https://blog.usejournal.com/express-like-framework-in-next-js-27a884a0264d">creating an Express-like framework in Next.js.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c03a216b0b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/next-js-using-cookies-in-getserversideprops-89c03a216b0b">Next.js — Using Cookies in getServerSideProps</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an Express-like Framework in Next.js]]></title>
            <link>https://javascript.plainenglish.io/express-like-framework-in-next-js-27a884a0264d?source=rss-fd0bc27f5dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a884a0264d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Justin Jaeger]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 22:59:17 GMT</pubDate>
            <atom:updated>2021-03-16T21:48:00.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acfsKMRrZSpogDM_FKEAUQ.jpeg" /></figure><p>In this article, I demonstrate how you can craft an Express-like API in Next.js without deploying an Express server with only a couple of adjustments.</p><p>If you’re looking for the benefits of Express’s framework but are happy with your application remaining serverless, this could be an option for you.</p><h3>Considerations for using Next.js</h3><p>I began my journey with Next.js because it makes server-side rendering for React straightforward. It allows me to easily choose what to render before page load, and has a pages folder for intuitive routing. I also discovered <a href="https://blog.newrelic.com/engineering/what-is-serverless-architecture/">other benefits of going serverless</a> like ease of deployment and focusing more on product development over managing servers.</p><blockquote><em>Want to read this story later? </em><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text"><em>Save it in Journal.</em></a></blockquote><p>This means less work on your end, but also less control. It’s useful to <a href="https://vercel.com/docs/platform/limits#">read the limitations</a> for the Vercel platform to see if it’s right for your application, taking note that there is a <a href="https://vercel.com/docs/platform/limits#">limit of 1000 concurrent requests</a> without an enterprise plan.</p><h3>Next.js’s API vs Expresss</h3><p>A primary concern for me was how I would architect my API. With <a href="https://vercel.com/docs/serverless-functions/introduction">Serverless Functions</a>, the ideal pattern is to have each route serve a single function in a single file in your pages/api directory (e.g. <strong>GET ‘/api/user/:id’</strong> ).</p><p>I was migrating from an Express environment and enjoy the logical flow of leaving functionality to the <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes">controllers</a>. My application had a custom authentication flow, so an endpoint like <strong>/api/login/</strong> would be too large to comfortably restrict to a single function. Not to mention that I want to reuse some of this functionality, so having this logic stored in isolated endpoints did not make sense to me.</p><p>The question became:</p><h3>Can I simply use Express with Next.js?</h3><p>Yes, but not without some tradeoffs.</p><p>One option is to set up a <a href="https://nextjs.org/docs/advanced-features/custom-server">custom server</a>, but this defeats some of the reasons to use Next.js in the first place, as you cannot deploy on Vercel and you’re no longer serverless. However, this is the right option for many applications, especially larger ones that benefit from managing their own server.</p><p>Another option is to <a href="https://vercel.com/guides/using-express-with-vercel">use Express within a serverless function</a>. Vercel recommends this only as a means to migrate your app and essentially ween yourself off of a dedicated server. Personally, I think it’s a bit silly to run Express in a serverless environment. It also means you are executing a full server implementation on each request, which violates the pattern of serverless functions serving one purpose. But I’m not suggesting this can’t work for you.</p><p>I decided to stay within the bumpers of Next.js and try to get the benefits I wanted out of Express’s framework without using Express.</p><h3>The problem I ran into</h3><p>I was set on having a controller directory in my app where I export a myriad of functions and call them like middleware from my serverless functions.</p><p>This is cumbersome to do in Next.js however, because it lacks a next() function that Express uses to <strong>escape</strong> the middleware chain and <strong>bypass</strong> the rest of the functionality.</p><p>Essentially, not having access to next() means I cannot easily break out of middleware early.</p><h3>What NOT to do:</h3><p>In this example, we have an endpoint that awaits the verification of a token before sending user data. If the middleware function tells us we are not verified, we need to handle that response and avoid executing the next middleware function.</p><pre><strong>/api/authenticateUser</strong></pre><pre>import authController from &#39;controllers/authController&#39;;</pre><pre>export default async (req, res) =&gt; {</pre><pre>try {</pre><pre><strong>  // Controller sends back a boolean &quot;verified&quot; and &quot;userId&quot;</strong><br>  const result = await authController.verifyToken(req, res);<br>  if (result.verified === false) {<br>    return res.json({ error: &#39;Not authenticated&#39;})<br>  };</pre><pre>  const payload = { userId: result.userId };</pre><pre><strong>  // Fetch user data by userId. Returns username<br></strong>  const data = await authController.header(req, res, payload);<br>  const { username } = data;</pre><pre>  return res.json({ username });</pre><pre>} catch(e) {<br>  return res.status(500).send(e.message);<br>}};</pre><p>As you can see, this looks nothing like the clean middleware chain we’re used to in Express. I have to pass information like { verified: true } back to the “awaiting” function in order to handle exceptions.</p><p>In express, we would just return something like next(err) or res.json({error: ‘custom error’ }) <strong>inside the controller, </strong>where, if we don’t hit the next() statement, we do not proceed. Here, if we call res.json() from the controller, it will return out of the function, but not end the response all together.</p><p>Also notice how clumsy it is not to have a res.locals object to pass data between. We have to pack data into a payload and unpack the results of every controller call.</p><h3>The Solution:</h3><p>(explanation provided below)</p><pre>import wrapper from ‘utils/wrapper’;<br>import authController from ‘controllers/authController’;</pre><pre>const handler = async (req, res, middlewareChain) =&gt; {</pre><pre>  await middlewareChain<br>  (<br>    authController.verifyToken,<br>    authController.getUserId,  <br>  )<br>  .then(result =&gt; { if (!result) return; })<br>  .catch(e =&gt; { res.status(500).send(e.message); })</pre><pre>  return res.json({<br>    username: res.locals.username<br>  });</pre><pre>};</pre><pre>export default wrapper(handler);</pre><p>This doesn’t explain much without showing you the wrapper function I import at the top. Just notice the fact that we are not exporting the function, but the wrapper with the function passed in.</p><h4>The Wrapper:</h4><p>Wrapping the function allows us to execute our function with modified res and req functions, as well as add any other functions to our parameters (like middlewareChain).</p><p>Here’s what the wrapper file looks like:</p><pre><strong>utils/wrapper</strong></pre><pre>const wrapper = handler =&gt; {</pre><pre>return (req, res, middlewareChain) =&gt; {<br>   <br>    <strong>/* res.locals object */<br>    </strong>res.locals = {};</pre><pre><strong>    /* middlewareChain function */<br>    </strong>middlewareChain = async (...funcs) =&gt; {<br>      let finished = true;<br>      for (const func of funcs) {<br>        await func(req, res)<br>        if (res.finished) {<br>          finished = false;<br>          break;<br>        };<br>      };<br>    return next;<br>    };</pre><pre>  return handler(req, res, middlewareChain);<br>  };<br>};</pre><pre>module.exports = wrapper;</pre><p>First, you’ll see we can declare and utilize <strong>res.locals </strong>in the same exact way we would with Express. This allows us to easily pass data between functions.</p><p>As for the <strong>middlewareChain</strong> function, this takes all of your controller functions as arguments. For each function, we await the response and check if we called res.json() or res.send() somewhere along the way. We check this by utilizing the <strong>res.finished </strong>property, native to the res object. Its value changes from true to false when you call res.json() or res.send(). (This is normally meant to ensure we don’t set the response twice ).</p><p>If I want to exit my controller function early, I can call <strong>return res.json({data})</strong>. My middlewareChain will catch that I want to return a response and break out of the loop. In addition to calling <strong>break</strong>, we also set a <strong>finished</strong> variable to false, making middlewareChain’s return value a boolean. We handle this response in <strong>.then()</strong>, saying if it evaluates false, return.</p><p>Of course, another way to break out of controller functions is to throw an error, but this is not appropriate for every situation.</p><h4>Other things you can do with a wrapper:</h4><p>In my application, I also have error handing and cookie handling functions (<strong>res.cookie</strong>) that I place on the response object, which I highly recommend. I’ve written an article on <a href="https://justinjaeger.medium.com/next-js-using-cookies-in-getserversideprops-89c03a216b0b">handling cookies in an express-like way here</a>.</p><p>Point is, you can attach any sort of function or object you want onto req and res that makes your life easier or takes out repetitive code.</p><h3>In conclusion</h3><p>This strategy could help you keep your Express-like workflow without creating a custom server <strong>and</strong> without sacrificing the ability to use controllers that can halt the “middleware” chain.</p><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a884a0264d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/express-like-framework-in-next-js-27a884a0264d">Create an Express-like Framework in Next.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>