<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NestJs Archives - Nerd Corner</title>
	<atom:link href="https://nerd-corner.com/tag/nestjs/feed/" rel="self" type="application/rss+xml" />
	<link>https://nerd-corner.com/tag/nestjs/</link>
	<description>Craft your dreams!</description>
	<lastBuildDate>Wed, 11 Dec 2024 13:10:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.2</generator>

<image>
	<url>https://nerd-corner.com/wp-content/uploads/2019/10/cropped-LogoNerdCorner-2-32x32.png</url>
	<title>NestJs Archives - Nerd Corner</title>
	<link>https://nerd-corner.com/tag/nestjs/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Lessons Learned: Hosting NestJS App on Vercel</title>
		<link>https://nerd-corner.com/lessons-learned-hosting-nestjs-app-on-vercel/</link>
					<comments>https://nerd-corner.com/lessons-learned-hosting-nestjs-app-on-vercel/#respond</comments>
		
		<dc:creator><![CDATA[Nerds]]></dc:creator>
		<pubDate>Thu, 14 Nov 2024 07:19:52 +0000</pubDate>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[config]]></category>
		<category><![CDATA[cookie-sessions]]></category>
		<category><![CDATA[CORS error]]></category>
		<category><![CDATA[Cors error nest]]></category>
		<category><![CDATA[database config]]></category>
		<category><![CDATA[database hosting]]></category>
		<category><![CDATA[express]]></category>
		<category><![CDATA[express-sessions]]></category>
		<category><![CDATA[express.js]]></category>
		<category><![CDATA[google cloud]]></category>
		<category><![CDATA[google cloud mysql]]></category>
		<category><![CDATA[Hosting]]></category>
		<category><![CDATA[internal server error vercel]]></category>
		<category><![CDATA[internal server error vercel nest]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lessons Learned]]></category>
		<category><![CDATA[mySql]]></category>
		<category><![CDATA[Nest]]></category>
		<category><![CDATA[Nest hosting issues]]></category>
		<category><![CDATA[NestJs]]></category>
		<category><![CDATA[Redis]]></category>
		<category><![CDATA[redis session management]]></category>
		<category><![CDATA[redis session management nest.js]]></category>
		<category><![CDATA[session management]]></category>
		<category><![CDATA[Step by step guide]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[Vercel]]></category>
		<category><![CDATA[vercel.json]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[with credentials]]></category>
		<guid isPermaLink="false">https://nerd-corner.com/?p=1621</guid>

					<description><![CDATA[<p>After spending hours getting my NestJS app up and running on Vercel, I figured it was time to document what I learned—not only to save &#8230; </p>
<p>The post <a href="https://nerd-corner.com/lessons-learned-hosting-nestjs-app-on-vercel/">Lessons Learned: Hosting NestJS App on Vercel</a> appeared first on <a href="https://nerd-corner.com">Nerd Corner</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>After spending hours getting my NestJS app up and running on Vercel, I figured it was time to document what I learned—not only to save myself time in the future, but hopefully to help others avoid some of the pitfalls I ran into. Here’s a breakdown of what worked, what didn’t, and how I finally got everything running smoothly.</p>
<p><em><strong>This might also be interesting for you:</strong> <a href="https://nerd-corner.com/import-swagger-in-node-typescript-project/" target="_blank" rel="noopener">Adding Swagger to Node Server</a></em></p>
<h3>Step 1: Setting Up NestJS Vercel hosting</h3>
<p>First things first, getting the basic setup to deploy on Vercel. Vercel is awesome for serverless, but working with NestJS needed a few tweaks. The main thing is to set up a <code>vercel.json</code> configuration file, which tells Vercel exactly how to handle your app.</p>
<p>Here’s the configuration I ended up with:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="beyond">{
  "version": 2,
  "builds": [
    {
      "src": "src/main.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "src/main.ts",
      "methods": [
        "GET",
        "POST",
        "PUT",
        "PATCH",
        "OPTIONS",
        "DELETE",
        "HEAD",
        "CONNECT",
        "TRACE"
      ]
    }
  ]
}
</pre>
<p>I deployed it to Vercel and got the following error:</p>
<pre>This Serverless Function has crashed. Your connection is working correctly. 
Vercel is working correctly. 500: INTERNAL_SERVER_ERROR 
Code: FUNCTION_INVOCATION_FAILED ID: bom1::sgk4v-1711014022883-1e9ed54f4c37</pre>
<p>Looking in the logs, I noticed the database connection was an issue and in addition got the following log message:</p>
<pre>No exports found in module "/var/task/app-name/src/main.js".
Did you forget to export a function or a server?</pre>
<p>Turned out I could ignore the second part of the error message and just focus on the database connection.</p>
<h3>Step 2: Configuring the Database</h3>
<p>For my app, I used a mysql database with multiple schemas. I tried several free offers, but they were not compatible with the multiple schemas approach. Therefore I ended up with hosting it on Google Cloud. I scaled it down to a price of 0.01$ per hour and used the 300$ newbie offer.</p>
<p>Allowing Vercel to connect required setting the IP to <code>0.0.0.0/0</code> in Google Cloud’s configuration, making the database accessible from any IP address. <strong>Important note</strong>: make sure you test locally before deploying to Vercel, or you’ll be dealing with errors like these:</p>
<h3>Step 3: Dealing with CORS</h3>
<p>CORS caused also some headaches. Make sure you allow <code>OPTIONS</code> for CORS preflight requests, as Vercel needed explicit permission for cross-origin requests. I ended up adding a lot of headers to make sure requests were allowed:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="beyond">app.enableCors({
    origin: 'domain-name',
    credentials: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    allowedHeaders: [
      'Origin',
      'X-Requested-With',
      'Content-Type',
      'Accept',
      'Authorization',
    ],
  });</pre>
<h3>Step 4: Switching to <code>express-session</code> and Redis for Session Management</h3>
<p>One of the trickiest parts was getting sessions to work. I started with the <code>cookie-session</code> library, but Vercel completely ignore it. After digging into the docs and some trial and error, I switched to <code>express-session</code>, which is more popular and works nicer with Vercel’s serverless environment.</p>
<p>For some reason the import syntax has to be exactly like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="beyond">import session = require('express-session');</pre>
<p>I also had to configure the session middleware with <code>trust proxy</code> enabled, since Vercel proxies requests. Here’s what the final setup looked like:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="beyond">const expressApp = app.getHttpAdapter().getInstance();
expressApp.set('trust proxy', true);</pre>
<p><span style="font-size: 1.125rem;">Also s</span>etting <code>secure: true</code> and <code>sameSite: 'none'</code> was essential to ensure cookies work across HTTPS and cross-origin requests!</p>
<p>Keep in mind, with Vercel, multiple serverless instances can handle requests simultaneously, which caused session conflicts. To fix this, I connected my session storage to a Redis instance. Luckily this was super easy.</p>
<p><a href="https://redis.io/">Redis</a> keeps session data consistent, avoiding conflicts across requests, especially under load. The code I ended up with:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="beyond">const expressApp = app.getHttpAdapter().getInstance();
expressApp.set('trust proxy', true);

const redisClient = createClient({
    password: process.env.REDIS_PASSWORD,
    socket: {
      host: process.env.REDIS_HOST,
      port: parseInt(process.env.REDIS_PORT, 10),
    },
  });

  redisClient
    .connect()
    .catch((err) =&gt;
      console.log('Could not establish a connection with Redis: ' + err),
    );

  redisClient.on('error', (err) =&gt; console.log('Redis error: ' + err));
  redisClient.on('connect', () =&gt;
    console.log('Connected to Redis successfully'),
  );

  app.use(
    session({
      store: new RedisStore({ client: redisClient }),
      secret: process.env.COOKIE_SECRET,
      cookie: {
        secure: process.env.NODE_ENV !== 'development',
        sameSite: process.env.NODE_ENV === 'development' ? 'lax' : 'none',
        maxAge: 86400000,
      },
    }),
  );</pre>
<p><span style="font-family: 'Roboto Condensed', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; font-size: 1.75rem;">Step 5: Add </span><code>withCredentials</code><span style="font-family: 'Roboto Condensed', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; font-size: 1.75rem;"> in the Frontend</span></p>
<p>This step is just a side note: For session cookies to work between the frontend and backend, <code>withCredentials</code> need to be set to <code>true</code> on my frontend’s HTTP requests. This allows cookies to be included in cross-origin requests, which is important when the frontend and backend are hosted separately. I had to make sure Angular’s HTTP client had this setting enabled.</p>
<h3>Step 6: Include font</h3>
<p>To include font files in your NestJS project, you can use the <code>compilerOptions</code> in the <code>nest-cli.json</code> file to define assets for build output, like specifying <code>"include": "**/*.ttf"</code> and <code>"outDir": "dist/src"</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-title="nest-cli.json" data-enlighter-theme="beyond">{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      {
        "include": "**/*.ttf",
        "outDir": "dist/src"
      }
    ],
    "deleteOutDir": true
  }
}</pre>
<p>After the build, ensure the fonts are correctly referenced in your code using <code>path.resolve</code>, e.g., <code>path.resolve(__dirname, '../fonts/Roboto-Regular.ttf')</code>. This approach ensures the font files are bundled with the build and accessible during runtime.</p>
<h3>Final Thoughts to NestJS Vercel hosting</h3>
<p>Deploying my NestJS app on Vercel was a true roller coaster. Sometimes, I felt like I was on the verge of getting everything working perfectly, only to be hit with new errors that sent me back to troubleshooting mode. There were moments of frustration—especially around the session handling and CORS issues. But each solution brought a new high, and every error fixed felt like a little victory.</p>
<p>Now, with everything finally working smoothly, I can say it feels awesome. Seeing my app live and functioning the way I envisioned is worth all the headaches. It’s a huge relief, but even more, it’s deeply satisfying to know I’ve overcome each hurdle and can look back on what I learned. I hope this guide can save others some of those low points and help them reach that “it just works” moment a little faster!</p>
<p>The post <a href="https://nerd-corner.com/lessons-learned-hosting-nestjs-app-on-vercel/">Lessons Learned: Hosting NestJS App on Vercel</a> appeared first on <a href="https://nerd-corner.com">Nerd Corner</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://nerd-corner.com/lessons-learned-hosting-nestjs-app-on-vercel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
