<?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 Ellert Smári Kristbergsson on Medium]]></title>
        <description><![CDATA[Stories by Ellert Smári Kristbergsson on Medium]]></description>
        <link>https://medium.com/@ellertsmarik?source=rss-8601d2548892------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pCnGLf493ZjyVdg4.</url>
            <title>Stories by Ellert Smári Kristbergsson on Medium</title>
            <link>https://medium.com/@ellertsmarik?source=rss-8601d2548892------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:46:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ellertsmarik/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[JSON API, using Next.js 13+ and MongoDB]]></title>
            <link>https://ellertsmarik.medium.com/json-api-using-next-js-13-and-mongodb-f45e8e61b031?source=rss-8601d2548892------2</link>
            <guid isPermaLink="false">https://medium.com/p/f45e8e61b031</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Ellert Smári Kristbergsson]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 00:05:13 GMT</pubDate>
            <atom:updated>2025-01-09T16:35:42.344Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a continuing tutorial from my “The MongoDB and Next.js Stack for Beginners” tutorial that you can find <a href="https://medium.com/@ellertsmarik/the-mongodb-and-next-js-stack-for-beginners-b4394872f5bb">here</a>. At this point you should have a project where you have been able to connect to your MongoDB database and get the data to show in your browser. In this tutorial I want to show how we would do the CRUD operation (Create Read Update and Delete) … or actually I will show you the CRU and when you have gone through that process you should know enough to deal with the D yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWOFvCU-1I8TJWsiLVibSw.png" /></figure><p>The only thing you need for this tutorial is everything we did in the previous tutorial. If you did not do that one you can get the code from my GitHub repository <a href="https://github.com/ellertsmari/The_MongoDB_and_Next.js_Stack_for_Beginners">here</a>. Before we dive into the code, let’s start by talking a bit about the addition here, namely the JSON API:</p><h4>JSON</h4><p>I am sorry if you feel that I am shouting at you but this is just an abbreviations and in the world of web development almost every other word is an abbreviation. JSON stands for JavaScript Object Notation because it is basically just a JavaScript object that we send between the back end and the front end. Be careful though, because you can not do everything in JSON that you can do with JavaScript objects, for example you can not use functions as properties (or methods).</p><h4>API</h4><p>API stands for Application Programming Interface and when we put it together like this we are just saying that the interface that the front end uses to talk to the back end is JavaScript objects. For us as JavaScript (or TypeScript) developers this is good news because that is a format we are well familiar with.</p><h4>Let’s get our hands dirty</h4><p>Now let’s dive into the code. We had created three routes in our code, back, front and database. Now we want to create an API on our server. This can be done using the Next.js <a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers">Route Handlers</a>. This method is much more conventional than using server side components and more like something you would see in other programming languages such as PHP or Python. In this tutorial we will use all the CRU(D) operations. Conveniently, they can be mapped onto their corresponding HTTP method like so: POST for Create, GET for Read, PUT (or PATCH) for Update and DELETE for Delete.</p><h3>GET</h3><h4>Front end</h4><p>Let’s start with the simplest one to do exactly what we had already done before, namely <strong>read</strong> from our database. We start by creating a folder for our api. In older versions of Next the api folder was special and you needed to call it api but now we can call it whatever we want. Hmmm… I know! let’s call it api (it actually makes the most sense anyway). Inside this folder we create a file called route.ts. The route.ts is a special file in Next.js in the way that functions exported from this file can use request as a parameter and will receive an object representing the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Request">request</a> to the server to that parameter. To demonstrate this we will create a basic GET function. The video below demonstrates how to create all this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3YL_-UayyAdj4yIDyJHKw.gif" /></figure><p>If you now go to your browser you should be able to see your new API on localhost:3000/api. Everything you do in a route.ts file happens on the server so you won’t see any console.logs in the browser or in any other way be able to effect the browser’s behavior. Another interesting thing that you can observe in the route.js file is that we have access to this Response object that we can use to send data as a response to the request that the browser sends to our server when the user navigates to our website.</p><h4>Back end</h4><p>Now let’s get that sweet, sweet database code in there that we had in the earlier tutorial. When we have finished copy-pasting that code our route.ts will look something like this:</p><pre>import { MongoClient, ServerApiVersion } from &#39;mongodb&#39;<br><br>    <br>const uri = process.env.MONGO_URI<br>if(!uri){<br>    throw new Error(&quot;environment variable MONGO_URI is not defined&quot;);<br>}<br><br>// Create a MongoClient with a MongoClientOptions object to set the Stable API version<br>const client = new MongoClient(uri, {<br>  serverApi: {<br>    version: ServerApiVersion.v1,<br>    strict: true,<br>    deprecationErrors: true,<br>  }<br>});<br><br>async function run() {<br>    try {<br>      // Connect the client to the server (optional starting in v4.7)<br>      await client.connect();<br>      // Querying our database<br>      const cursor = await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).find();<br>      const array = await cursor.toArray()<br>      return array;<br>    } finally {<br>      // Ensures that the client will close when you finish/error<br>      await client.close();<br>    }<br>  <br>  }<br>export async function GET(request: Request) {<br>    const greetings =  await run();<br>    return Response.json(greetings)<br>  }</pre><p>Now if you go to localhost:3000/api you will see the data from your database. How cool is that!?! We have just made an API that holds all the data from our database. Now let’s clean this up a bit. We don’t want to be connecting to- and disconnecting from the database all the time so we want to move that logic out of the api. So let’s put our src directory to use. In the src directory, create a new folder called utils inside that folder create a file called startMongo.ts . In that file we add some code that I must admit that I actually stole it from this <a href="https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/lib/mongodb.ts">example</a> in the official Next.js repository. This is how that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DytIxKQNdvgH52nFPRuZ8A.gif" /></figure><h4>Clean up</h4><p>It is not always good to steal and I can see that the code has not been updated according to MongoDB newest guidelines so we need to add the code to support their new “<a href="https://www.mongodb.com/docs/drivers/node/current/fundamentals/stable-api/">Stable API</a>” so the code in our startMongo.ts becomes like this:</p><pre>import { MongoClient, ServerApiVersion } from &#39;mongodb&#39;<br><br>if (!process.env.MONGODB_URI) {<br>  throw new Error(&#39;Invalid/Missing environment variable: &quot;MONGODB_URI&quot;&#39;)<br>}<br><br>const uri = process.env.MONGODB_URI<br>const options = {<br>    serverApi: {<br>    version: ServerApiVersion.v1,<br>    strict: true,<br>    deprecationErrors: true,<br>  }<br>}<br><br>let client<br>let clientPromise: Promise&lt;MongoClient&gt;<br><br>if (process.env.NODE_ENV === &#39;development&#39;) {<br>  // In development mode, use a global variable so that the value<br>  // is preserved across module reloads caused by HMR (Hot Module Replacement).<br>  let globalWithMongo = global as typeof globalThis &amp; {<br>    _mongoClientPromise?: Promise&lt;MongoClient&gt;<br>  }<br><br>  if (!globalWithMongo._mongoClientPromise) {<br>    client = new MongoClient(uri, options)<br>    globalWithMongo._mongoClientPromise = client.connect()<br>  }<br>  clientPromise = globalWithMongo._mongoClientPromise<br>} else {<br>  // In production mode, it&#39;s best to not use a global variable.<br>  client = new MongoClient(uri, options)<br>  clientPromise = client.connect()<br>}<br><br>// Export a module-scoped MongoClient promise. By doing this in a<br>// separate module, the client can be shared across functions.<br>export default clientPromise</pre><p>Now that we have that out of the way we can simplify our api/roue.ts . Everything that was there before the run function has been moved to the startMongo.ts file so we can take that out. We can also get rid of the run function itself because we can just move database related code into the GET function. Just look how satisfyingly beautiful our api/route.ts file has become:</p><pre>import connect from &#39;@/utils/startMongo&#39;<br><br>export async function GET(request: Request) {<br>  const client = await connect<br>  const cursor = await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).find();<br>  const greetings = await cursor.toArray()<br>  return Response.json(greetings)<br>}</pre><figure><img alt="Sooo goood" src="https://cdn-images-1.medium.com/max/659/1*qMsZKYc3L3DVjcz83bIN4A.jpeg" /></figure><p>This is too good. We have to add more chaos to that file. Let’s make our POST method there and make it so that we can add data to the database. Now the first two lines are going to be very similar since we still want to make sure that we are connected to the database and we want to work with the same database and the same collection.</p><h4>POST</h4><h4>Back end</h4><p>This time we don’t want to use the find method. We should probably look for a suitable method in the documentation. Something like <a href="https://mongodb.github.io/node-mongodb-native/6.3/#md:insert-a-document">this</a> . There is a method called insertMany, but there also exists a method called insertOne and that is the one we are going to use. Since this is a document based database we just pass this method an object with the property we want to insert (greeting) and the value we want for the new entry, let’s make it “Good bye cruel world” as oppose to the hello that we had before. Finally we respond with something like a message saying that the update was successful. Our POST method should be added to our api/route.ts and it should look like this (watch out not to replace the code in api/route.ts but only to add this code):</p><pre>export async function POST(request: Request){<br>  const client = await connect;<br>  const cursor = await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).insertOne({greeting:&quot;Goodbye cruel world&quot;});<br>  return Response.json({message: &quot;successfully updated the document&quot;})<br>}</pre><p>This looks good. But how do we know if it works or not? If we go to localhost:3000/api our browser always makes a GET request to the server so we are not going to see what happens in the POST request. This time we need to make some front-end code to try it out.</p><h4>Front end</h4><p>Let’s try to add some fetch call to our front-end code under the front route. For that we will need some front-end only code and the only way to do that in Next.js is to put it into our useEffect hook. We will also need to tell fetch that we want it to send a post request since, like the browser, it sends a get request by default. This is what it looks like:</p><pre>&#39;use client&#39;<br>import { useEffect } from &quot;react&quot;<br><br>export default function Front() {<br>  useEffect(()=&gt;{ <br>    fetch(&#39;/api&#39;,{method:&quot;POST&quot;})<br>  })<br>  return (&lt;h1&gt;Some content&lt;/h1&gt;)<br>}</pre><p>Woohoo! Now you can open a new tab, navigate to localhost:3000/front and the database should get a new entry. Every time we refresh our page there comes a new entry to our database (because the code in front/page.tsx is running). Let’s make it even more awesome! Let’s make a input field where people can write their own greetings that will appear in the database. We will also need a “send” button so we know when the user is ready to send the greeting to the database. We will need some react state to keep track of what the user writes into the input field (<a href="https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable">a controlled input</a>) and of course, like always in the front end, we will need an onClick event on the button to trigger the fetch call to the server. The good news is that we can get rid of our useEffect. Now our front/page.tsx will look like this:</p><pre>&#39;use client&#39;<br>import { useState } from &quot;react&quot;<br><br>export default function Front() {<br>  const [greeting, setGreeting] = useState(&quot;&quot;);<br>  const saveGreeting = ()=&gt;{<br>    fetch(&#39;/api&#39;,{<br>      method:&quot;POST&quot;, <br>      //The client can only send strings to the server<br>      //so we need to change our whole object to a string<br>      body:JSON.stringify({greeting})<br>    })<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;input value={greeting} onChange={(e)=&gt;setGreeting(e.target.value)}/&gt;<br>      &lt;button  onClick={saveGreeting}&gt;send my greeting to the server&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Finish up in the back</h4><p>Nice front end. But wait a minute… Even though our back end is getting the users greeting it is still just sending our hard coded greeting to the database. We need to change the server as well. Finally we can use the request parameter. The request object has a method called json() that looks at the string (our stringified object in the body), turns it back into an object and returns that object. This is an asynchronous function so we need to “await” it. Then when we have got the object, we can just send our greeting straight to the database the same way we did with our hard coded greeting, like this:</p><pre>export async function POST(request: Request){<br>  const client = await connect;<br>  const body = await request.json()<br>  await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).insertOne({greeting: body.greeting});<br>  return Response.json({message: &quot;successfully updated the document&quot;})<br>}</pre><p>Wow. Now whatever we send from the front end turns up in our database, what a powerful thing to have. But with great power comes great responsibility and normally you would want to protect this kind of behavior so that only registered users could effect the content of your database but that is outside the scope of this tutorial. Now that we are able to write to our database let’s continue to the edit or update or PUT part.</p><h3>PUT</h3><h4>Back end</h4><p>First thing is first, so let us start by checking the MondgoDB documentation on how to update stuff in our database <a href="https://mongodb.github.io/node-mongodb-native/6.3/#md:update-a-document">here</a>. This will be very similar to our other methods (GET and POST). The main difference is that we will use the updateOne method from the documentation on our collection and that method takes two arguments, first one stating what you want to change (often it is good to use the _id to make sure you are updating the correct one).</p><p>Now we just need an id to be able to try this out. That is not a problem because if you go to localhost:3000/api you will see some ids that you can use to try to change one of the greetings. Copy one of the ids. Ideally we would just pass it into the first argument but ids are not just normal strings in MongoDB but an ObjectId. We therefore need to import ObjectId from mongodb, make a new variable (we can call it id) and create a new ObjectId from the string that we just copied. Now we can pass {_id:id} as the first argument to our updateOne method and use a similar object as we had in our insertOne method in the POST as the second argument except according to the <a href="https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/">documentation</a> we need to put a $set property before our object so the second argument will be something like { $set: {greeting: &quot;this greeting has been updated&quot; } } . After doing this the api/route.tsx file should look like this:</p><pre>import connect from &#39;@/utils/startMongo&#39;<br>import { ObjectId } from &#39;mongodb&#39;<br><br>export async function GET(request: Request) {<br>  const client = await connect<br>  const cursor = await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).find();<br>  const greetings = await cursor.toArray()<br>  return Response.json(greetings)<br>}<br><br>export async function POST(request: Request){<br>  const client = await connect;<br>  const body = await request.json()<br>  await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).insertOne({greeting: body.greeting});<br>  return Response.json({message: &quot;successfully updated the document&quot;})<br>}<br><br>export async function PUT(request: Request){<br>  const client = await connect;<br>  const id = new ObjectId(&quot;659fcf9cc861d2ffb04fe17c&quot;)<br>  await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).updateOne({_id: id}, {greeting:&quot;this greeting has been updated&quot;});<br>  return Response.json({message: &quot;successfully updated the document&quot;})  <br>}</pre><p>Remember to use an id from your own database because the one in the code here above is from my database, your database will not have the same ids as mine. Now we just need some way of testing it out if it works. We don’t want our users to deal with ids from our database so it is probably a good idea to start by getting our greetings from the database and let our users select what greeting they want to change. We can use our back route to do that.</p><h4>Front end</h4><p>This will be a bit of a blend of our database/page.tsx and our front/page.tsx file. We have a fetch call like in our front route but now we are getting some data from there and TypeScript wants to know what kind of data there is so let’s create the type for it and call it “Greeting”. Also in a server side component you can not use relative urls so we need to add the base url in front of it. After doing all this our back/page.tsx looks like this:</p><pre>//since we are using TypeScript we need to declare our type first<br>type Greeting = {<br>  greeting:string;<br>  _id: string;<br>}<br>export default async function Back() {<br>  const baseUrl = &quot;http://localhost:3000&quot;<br>  const response = await fetch(`${baseUrl}/api`)<br>  const greetings: Greeting[] = await response.json()<br>  return (<br>    &lt;div&gt;<br>      {greetings.map(greetingObj=&gt;<br>        &lt;h1 key={greetingObj._id.toString()}&gt;<br>          {greetingObj.greeting}<br>        &lt;/h1&gt;<br>      )}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>It is better to store the baseUrl variable in the .env file because it needs to be different in production than in development since our server will not be running on localhost forever. But for the sake of simplicity of this tutorial I will keep it in the same file. Now if you open localhost:3000/back in your browser you will see all the greetings and we want our users to be able to choose a greeting to change/edit it. For this we need some interactive elements but we are in a server side component so what do we do? The trick is to make a component for the interactive part of our page and put the ‘use client’ in there. That way we get the best of both worlds: getting the data straight from the database and interactivity, could it get any better than this?</p><h4>Front end</h4><p>So let’s dive in. We should make a folder for our components because typically you will end up with quite a few of them. Lets call it “components” and put it into our app directory. Inside the components folder we can now make a file that holds our new component. Let’s call it editGreeting.tsx and let’s put the code for our greetings in there. We will need to pass the greeting object (greetingObj) to it as props and change the code in our back/page.tsx file accordingly. This is what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhSU7P1NdjF1XQiHkYfFzQ.gif" /></figure><p>I am not going to give you the code just yet because there are still a few things to fix. This component would work fine if this was JavaScript but we should make a type for the props so that TypeScript knows what is going on here and we still need to add our ‘use client’ directive after all that our editGreeting.tsx will look like this:</p><pre>&#39;use client&#39;<br><br>type Props = {<br>    greetingObj: {<br>        _id: string;<br>        greeting: string;<br>    }<br>}<br>const EditGreeting = ({greetingObj}:Props)=&gt;{<br>    return (<br>        &lt;h1 key={greetingObj._id.toString()}&gt;<br>            {greetingObj.greeting}<br>        &lt;/h1&gt;)<br>}<br>export default EditGreeting</pre><p>Now we just need to import it and pass the props to our new component so that our back/page.tsx file will look like this:</p><pre>import EditGreeting from &quot;../components/editGreeting&quot;<br>//since we are using TypeScript we need to declare our type first<br>type Greeting = {<br>  greeting:string;<br>  _id: string;<br>}<br>export default async function Back() {<br>  const baseUrl = &quot;http://localhost:3000&quot;<br>  const response = await fetch(`${baseUrl}/api`)<br>  const greetings: Greeting[] = await response.json()<br>  return (<br>    &lt;div&gt;<br>      {greetings.map(greetingObj=&gt;<br>        &lt;EditGreeting greetingObj={greetingObj} key={greetingObj._id.toString()}/&gt;<br>      )}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>If you are a pro programmer you might have spotted that we have a little redundancy in our code and we are breaking the DRY principle by having the same code in both files, namely { greeting:string, _id:string } . I will leave it as an exercise for the reader to abstract this code out of here and put it into it’s own file. If you now go to localhost:3000/back you will see that nothing has changed. Everything works exactly the same way as before. If you would be doing this for a client he would be furious that you spent all this time for nothing. But we know that now we can make our site interactive because we have a client side component within our server side page!</p><p>Let us start by adding an input and a submit button next to all of the greetings. We will have it as a controlled input and make a click event for the button like we did in the POST request. Also we will need to put the _id with in the body before we send it off to the server because the server will need to know witch greeting it should update. After all these changes our editGreetings.tsx file will look like this:</p><pre>&#39;use client&#39;<br>import { useState } from &quot;react&quot;<br><br>type Props = {<br>    greetingObj: {<br>        _id: string;<br>        greeting: string;<br>    }<br>}<br>const EditGreeting = ({greetingObj}:Props)=&gt;{<br>    const [greeting, setGreeting] = useState(&quot;&quot;);<br>    const changeGreeting = ()=&gt;{<br>        fetch(&#39;/api&#39;,{<br>            method: &quot;PUT&quot;,<br>            body: JSON.stringify({ greeting, id:greetingObj._id })<br>        })<br>    }<br>    return (<br>        &lt;div key={greetingObj._id.toString()}&gt;<br>            &lt;h1&gt; {greetingObj.greeting} &lt;/h1&gt;<br>            &lt;input <br>                value={greeting}<br>                onChange={(e)=&gt;setGreeting(e.target.value)}<br>            &gt;&lt;/input&gt;<br>            &lt;button onClick={changeGreeting}&gt;change this greeting&lt;/button&gt;<br>        &lt;/div&gt;<br>    )<br>}<br>export default EditGreeting</pre><h4>Finishing up in the back</h4><p>Now we need to change the server so that it can use our client side provided data to update the database. Let’s head to our api/route.ts file and change the hardcoded id into the id that comes from the request body and the greeting into the greeting from the request body. Finally our PUT method will look like this:</p><pre>export async function PUT(request: Request){<br>  const client = await connect;<br>  const body = await request.json()<br>  const id = new ObjectId(body.id)<br>  await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).updateOne({_id: id}, { $set: {greeting:body.greeting}});<br>  return Response.json({message: &quot;successfully updated the document&quot;})  <br>}</pre><p>If you now head to localhost:3000/back in your browser and write something into one of the textboxes and submit it with the submit button you will see it changing in the database. It will not change on the page though because the page has cached it and you will need to do a hard refresh to see it. To do a hard refresh on a Linux or Windows computer you can hold in the <strong>ctrl</strong> button and press <strong>f5</strong> at the same time if you are on a Mac computer you will need to hold the <strong>command</strong> and <strong>shift</strong> buttons and press <strong>R</strong>. Now you should see the new change that you made on your page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDkWcJ1gDpAyGgJBTQR6gQ.png" /></figure><p>Congratulations! your users can now read, write and update your database the only thing left for you to do now is to create the DELETE method. I won’t do that here since it is mostly a repetition of what we have already done and it is also a very good exercise to try out your new skills.</p><p>Other things you could try is to change the cashing strategy so that the page will change next time you refresh it without needing to do a hard refresh. <a href="https://nextjs.org/docs/app/api-reference/functions/fetch#optionscache">Here</a> is a very nice read of the cash option that you can pass to the fetch function to change the cashing strategy. You could try adding authentication to your site, A good place to start for that is <a href="https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#authentication-and-authorization">here</a>. You could also try hosting the site on Vercel to share it with the rest of the world and <a href="https://vercel.com/solutions/nextjs">here</a> is a guide for that. Whatever you do I recommend adding some data to the database and try to do CRUD on that as well. Also make sure to add some routes to the api folder (by adding a folder and a route.ts file into it similar to our folder/page.tsx routes)</p><p>The possibilities are endless now that you have a database and know how to do the CRUD operations on it. There is nothing you can not do and I am not even joking, all web applications are based on those operations you can do anything you want now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mvUykbfxjg8fErDTJWOag.png" /></figure><p>Thank you for staying with me throughout this tutorial. If you find something unclear or something I could do better I would be very thankful if you would leave a comment telling me about it. Also if you decide to do some of the stuff I have suggested you could do after the tutorial I would love to hear some stories or if you would like another tutorial like this on any of those topics ;-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f45e8e61b031" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The MongoDB and Next.js Stack for Beginners]]></title>
            <link>https://blog.stackademic.com/the-mongodb-and-next-js-stack-for-beginners-b4394872f5bb?source=rss-8601d2548892------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4394872f5bb</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs14]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ellert Smári Kristbergsson]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 15:27:43 GMT</pubDate>
            <atom:updated>2024-01-23T10:04:05.781Z</atom:updated>
            <content:encoded><![CDATA[<p>Here I will attempt to explain step-by-step, how to set up a full-stack project with MongoDB and Next.js. This article is made for students in the <a href="https://en.tskoli.is/skoli/reykjavik-academy-of-web-development/">Reykjavík Aca­demy of Web Develop­ment</a> but of course everybody is welcome to read it and use it as a source for their own projects. If you get stuck on any of the steps of this tutorial please let me know so that I can fix it and make it better.</p><h3>What is MongoDB?</h3><p>MongoDB is a database and as such it is a way to persist your data, meaning that you can create a website where users can change the content and save it as such and even share it with other users on your website. For example this site that I am using to write this article uses a database to store the article and if I refresh the page, my article will still be here because it is stored in the database. Another example would be a web-shop where admins can add products and remove products or a game where players can store their progress. The possibilities are endless!</p><h4>Databases vs CMS</h4><p>Some people might say <em>“Why don’t you just use a CMS (Content Management System) like WordPress?”</em> and of course that is fine if it suits your project but for smaller projects you might prefer to keep things simple, specially if you want to have full control over your code and understand what is going on. If your project is very large you might also prefer to connect straight to a database since it gives you more flexibility. CMS systems are often made for certain types of websites like web-shops or blogs and if you find one that fits well to your project you should probably just go with that.</p><h4>MongoDB vs other databases</h4><p>MongoDB is a non-relational (NoSQL), document based database, meaning that it has different structure than conventional databases. MongoDB is more convenient for web developers who are used to code in JavaScript because it stores all the data in JSON (JavaScript Object Notation) format so what you see in there are just JavaScript objects. There are also other document based databases out there but MongoDB is one of the most popular once and it is also convenient for students since they offer a free cloud solution on their Atlas cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-VAEaOFP5-qbQARXO7odg.png" /></figure><h3>What is Next.js?</h3><p>Next.js is a framework for React <em>“what?!? a framework for a framework?” </em>you might ask and you would be right. Next.js is a framework for React because it changes the way we work with React, just as React is a framework for JavaScript because it changes the way we work with JavaScript. Next.js helps us to enhance performance and SEO (Search Engine Optimization) by choosing how we render our content. It also enables us to easily write server side JavaScript code along side our client side code.</p><h4>Client side code / front end</h4><p>When we write JavaScript in files that are connected to our HTML document via a &lt;script&gt; tag or when we write in React it is all client side code (AKA front end) because that code runs in the browser on the hardware that our users are using on their computers. Client side code has access to the DOM and can change the UI interactively. It has no access to the operating system or databases. All the code written on the client side can be seen through code inspection tools in the browser. That is why you should avoid handling passwords and sensitive data on the client side.</p><h4>Server side code / back end</h4><p>Server side code (AKA back end) on the other hand runs on the web-server where the page is hosted, while you are developing and running it on localhost (or 127.0.0.1), your own computer will act as a web-server. Server side code has access to the computers operating system and can access databases but it can not access the DOM interactively. To sum it up: Code that updates the UI dynamically should be written on the client side. Code that handles sensitive data or data from the database should be written on the server side</p><h3>Let’s get started!</h3><p>Before you can start you will need to make sure that NodeJS and yarn are installed on your system. You can do this by typing in the commands node --version if you see the letter v followed by some numbers separated by dots you have NodeJS installed. If not, you will need to install it first <a href="https://nodejs.org/en/">here</a>. After installing NodeJS you will have the default <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> called npm. In this tutorial I will be using a different package manager called yarn but it is easy to install it using npm by typing npm install -g yarn into the terminal. If you are on a Mac computer you will probably need to do sudo before like sudo npm install -g yarn .</p><h3>Diving into it</h3><p>Let’s start by opening up a terminal window in the directory where you store your projects (or wherever want your project to be). From there you run the command yarn create next-app. This will create a new directory and initialize a new Next.js project in that directory. When you run the command You will be asked a few questions as shown in the video here below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJkk2wS7wTnpkjzfe2BjsQ.gif" /></figure><p>The questions are:<br><strong>What is your project named? </strong>— Name your project what you want. I named mine nextmongo and I will be refering to the project name by nextmongo from now on so if you chose another name make sure to replace nextmongo with that name wherever you see nextmongo in this tutorial.<br><strong>Would you like to use TypeScript?</strong> - In this tutorial I will be using TypeScript so I answer Yes here.<br><strong>Would you like to use ESLint?</strong> — You can chose what you want here but when I am working alone I prefer not to use lint and that is why I chose No here<br><strong>Would you like to use Tailwind CSS? </strong>I will not use any styling in this tutorial so it does not matter what you put here<br><strong>Would you like to use `src/` directory?</strong> I chose Yes here but you can chose whatever, it will not effect the outcome of the tutorial<br><strong>Would you like to use App Router?</strong> This is the new router from Next.js and they recommend that one so I will use that in this tutorial<br><strong>Would you like to customize the default import alias (@/*)?</strong> I chose No here.</p><p>After answering the questions you should have everything you need installed and you can open the project by typing code nextmongo in the terminal (remember that if you chose a different name for your project you write that instead of nextmongo)</p><h4>Making sure that everything works</h4><p>If everything works you should have the same file structure as shown in the video here below and you can then run the command yarn run dev to start the server. After that you should be able to go to your browser and enter the address localhost:3000 and then you should see the starting page for Next.js. Congratulations! you got everything set up and are ready to start coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZT4omnp2Hzp9BjYpo46sA.gif" /></figure><h3>The three hellos</h3><p>Now that we have got this monster up and running let’s test it out. Under normal circumstances we would just print out “hello world” to test our code because that is the convention when trying out something new. But this is not just one new thing, now we have front-end and a back-end so let’s try to get a hello from both of them and then try to isolate each of them and get a hello from only one at a time. We start with doing both at the same time:</p><h4>Hello both</h4><p>You can play around with the code in page.tsx if you like and I heavily recommend going through the official <a href="https://nextjs.org/learn?utm_source=next-site&amp;utm_medium=homepage-cta&amp;utm_campaign=home">Next.js tutorial</a> to understand the full potential of the framework. It is a very well written and interactive tutorial (almost as good as this one). But right now we are just interested in the shortest way to get this to work. Let’s start by editing the file called page.tsx in the src/app directory. In there we erase all the code and replace it with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHKZ9ipwqsMLxdu9BS9wSw.gif" /></figure><pre>&#39;use client&#39;<br><br>export default function Both() {<br>  console.log(&quot;hello both&quot;)<br>  return (&lt;h1&gt;Some content&lt;/h1&gt;)<br>}</pre><p>Now if you go to localhost:3000 (in your web browser) you should see a page where it says “Some content” and if you right-click on the page and choose “inspect” you will see the development tools open up. Now choose “console” and refresh your page, you should see the “hello both” text in the developer console.</p><p>Now go back to your VSCode and look at the terminal you will see the same message in the terminal. This is because even though we requested this page to be client side rendered, Next will first render it from the server and then again from the client to get all the content as quickly as possible to the user and to make the site more SEO friendly. The message you see in the terminal comes from the back-end and runs on the computer that hosts the website but the message you see in the browser comes from the front-end and runs on the computer that is visiting the website.</p><h4>Hello front</h4><p>Some times we want our code run only on the client side and not on the server that is mostly when we are working with some browser specific things, like for example localStorage. To make our code only run on the client we need to wrap it with the useEffect function. Let’s do that without loosing the code we had for the “hello both”. Create a new route by creating a new folder inside src/app. Let’s call this folder “front”. Inside the folder we then create a file called page.tsx and write our code there like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6_d48xXU-wRPdspREk8AQ.gif" /></figure><pre>&#39;use client&#39;<br>import { useEffect } from &quot;react&quot;<br><br>export default function Front() {<br>  useEffect(()=&gt;{ <br>    console.log(&quot;hello front end&quot;)<br>  })<br>  return (&lt;h1&gt;Some content&lt;/h1&gt;)<br>}</pre><p>Now if you go to your browser and open up localhost:3000/front you will see the “hello front end” appear in the developer console but it will not log out to the terminal of your VSCode.</p><h4>Hello back</h4><p>The back end is very similar except the code now only runs on the back-end but not in the front-end. You start by creating a new route by making a folder in src/app called back and inside that folder you create a file called page.tsx, just like we did before. Inside that file (src/app/back/page.tsx) we write the following code:</p><pre>export default function Back() {<br>  console.log(&quot;hello back end&quot;)<br>  return (&lt;h1&gt;Some Server Side rendered content&lt;/h1&gt;)<br>}</pre><p>Now if you go to your browser and enter localhost:3000/back you should see the new page but this time you will not see the “hello back end” in the console but only in the terminal in your VSCode, this is because we have not used the ‘use client’ directive in the top of our page.tsx file and by default all components in Next.js are server side components.</p><h3>Connecting the database</h3><p>Our next step here is to create a database and weapon of choice this time is MongoDB. The simplest way to set up such a database is to go sign up for the free cloud database at <a href="https://www.mongodb.com/cloud/atlas/signup">MongoDB Atlas</a>.</p><p>The First time you sign up there you will be asked to go through a few steps to set up your account. In one step you are asked to choose your preferred programming language and there you can choose JavaScript. After the registering you will get a large green button offering you to create a new database. You should do that and in that process you will be asked to choose a password. You need to copy that password and remember it since we will be using it later in this tutorial. Other than that you can write/choose what ever you want.</p><p>Once you have done that you will arrive to a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GRo0syWD8uy6aD4N.png" /></figure><p>Select the areas marked with red circles. Select a username and password and click Create User. To get the IP Address that you need to put into the IP Address field at the bottom, you can google “what is my ip” and it will show you something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QQaWxvV5hojtGUj1.png" /></figure><p>When you have entered your IP Address and given it a name in the description (if you are at home a good idea would be to put “home” in the description, if you are at school you can put “shcool”) and clicked the “Add Entry” button you should see the IP Address there below. If you see it there you can continue by clicking the “Finish and Continue” button in the lower, right corner. You will get a pop-up window where you can click “Go To Database” where you will be greeted with this window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D04QHEW93rPu00_k4g1R2A.png" /></figure><p>There you will be presented with five options, choose the one on the top with the title “Connect your application”. Now you will be presented with instructions on how to connect the database to your application. If you tick into the box next to “View full code sample” you will be able to copy most of the code that you need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*6wKkA0Ld-W4OzTfANmfm8g.png" /></figure><h4>Testing the connection</h4><p>Now that we have the code we can create a new route to test out our database. Let’s do that by creating a folder called database (in our app folder like front and back before) and guess what comes inside that folder… Yes you are right, a file called page.tsx. In that file you can now paste in the code you copied here above but this code is made for Node.js so it will need a few changes.</p><p>The first step is to replace the part in our code where it says “&lt;password&gt;” and write your own MongoDB Atlas password (that you copied before) there. If you don’t remember your password you can use the “Database Access” link in the sidebar to fix it. When you change the “&lt;password&gt;” Remember to take out the “less than sign” ( &lt; ) and also the “larger than sign” ( &gt; ) they should not be a part of the uri ). As an example: if your username is john and your password is 1234 the uri should start like “mongodb+srv://john:1234@cluster0….” . The second step is to change how we add external libraries to our code because in Next.js we use imports but not require like in the code given by Atlas. So the first line becomes import { MongoClient, ServerApiVersion } from &#39;mongodb&#39;. Now the last thing we need to do to make this work is to add the React component, since this is a Next.js route it expects us to export a React component. After all we should have a code that looks like this:</p><pre>import {MongoClient, ServerApiVersion} from &#39;mongodb&#39;<br>    <br>const uri = &quot;mongodb+srv://YOURUSERNAME:YOURPASSWORD@cluster0.lmfjbot.mongodb.net/?retryWrites=true&amp;w=majority&quot;;<br><br>// Create a MongoClient with a MongoClientOptions object to set the Stable API version<br>const client = new MongoClient(uri, {<br>  serverApi: {<br>    version: ServerApiVersion.v1,<br>    strict: true,<br>    deprecationErrors: true,<br>  }<br>});<br><br>async function run() {<br>  try {<br>    // Connect the client to the server (optional starting in v4.7)<br>    await client.connect();<br>    // Send a ping to confirm a successful connection<br>    await client.db(&quot;admin&quot;).command({ ping: 1 });<br>    console.log(&quot;Pinged your deployment. You successfully connected to MongoDB!&quot;);<br>  } finally {<br>    // Ensures that the client will close when you finish/error<br>    await client.close();<br>  }<br>}<br><br>export default function Database() {<br>    run().catch(console.dir);<br>    return (&lt;h1&gt;Trying out the database&lt;/h1&gt;)<br>  }</pre><p>Note that you need to use your own uri string because my username, password and the path after the “@“ will be different from yours but everything else you can copy and paste from the code above.</p><p>There is still one more thing we need to do before we can go on and create our database and that is to install the mongodb module. But as mentioned earlier installing a new module is an easy task. Simply type yarn add mongodb in your terminal (you might need to stop the server first but that is done by holding in the “Ctrl” key on your keyboard and pressing “c” at the same time). To make sure that the module has been installed you can check your package.json file and see if you can find it there. If it is not there you should try again. To start your server again write yarn run dev into your terminal.</p><p>Now if you open up your browser and type in localhost:3000/database you should be able to see “Pinged your deployment. You successfully connected to MongoDB!” in the terminal in your VSCode. If that is not the case try to scroll up in this tutorial and see if there is something you might have done wrong.</p><h4>Setting up the database</h4><p>Now let’s turn back to the MongoDB Atlas page. If you close the modal you will get back to the page where we started. This time we want to select the Database option from the sidebar and click the Browse Collections button from there. This will take us to a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heHopgwiwEAW3thjEQVRVQ.png" /></figure><p>You will get a pop-up offering you to use demo data or add your own. Since we are trying to learn how to make our own database you should click “Add My Own Data”. Now let’s name the database <strong>test</strong> and the collection <strong>greetings</strong> and click the green button that says “create”. Now the database will appear in the list on the left. You can open it by pressing the small gray arrow in front of it’s name (test) like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*WeRYaJaGnmfrEo4J.png" /></figure><p>Now if you click “greetings” you will get up the view that we can see here above. Now let’s add two documents to the collection by clicking the “INSERT DOCUMENT” button that you can see there on the right side. You will get a modal looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Y1rcfDj4HCAKSrYH.png" /></figure><p>There will be and _id property already filled in by default but then we can add more properties. Let’s add one called greeting that holds the value “Hello World MongoDB” like you can see above and then press the green button that says “Insert”.</p><p>If you have moved your server (in this case your computer) from one house to another (for example to the school) you will need this step:</p><p><em>Allow the ip address from our server. In this case it is probably just your own computer. Then we can click the “Network Access” in navbar on the left shown with a red circle on the picture here below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbWClP1AHCTLORyIwVDofw.png" /></figure><p><em>And then you click the green button there in the middle. After that you can click the “ADD CURRENT IP ADDRESS” and then the green button in the lower right corner where it says “Confirm”.</em></p><p>Now that you have all your settings ready we just need a small adjustment to the code and then we are ready to go! Let’s open our src/app/database/page.tsx file where we made our database route and change the line where it says await client.db(&quot;admin&quot;).command({ping: 1 }); . This line sends a ping to a database called admin just to test that our connection is working but we want to get the data that we just created in our database so we need to change the database from admin to test and replace the command method with the collection method to tell MongoDB what collection we want to be working with. Finally we call the find method on that collection to get the data from our collection. This find method returns an object that they call a MongoDB curs or just cursor. We need to store that cursor in a variable that we can call greetings.</p><p>Now that we have got our cursor we can use the toArray method to get a normal JavaScript array from it that is a more familiar form to most of us. Lastly we return that array from the function, call it in our component and map through it to display our greetings to the user. When we have done all that our code will look something like this:</p><pre>import {MongoClient, ServerApiVersion} from &#39;mongodb&#39;<br>    <br>const uri = &quot;mongodb+srv://YOURUSERNAME:YOURPASSWORD@cluster0.lmfjbot.mongodb.net/?retryWrites=true&amp;w=majority&quot;;<br><br>// Create a MongoClient with a MongoClientOptions object to set the Stable API version<br>const client = new MongoClient(uri, {<br>  serverApi: {<br>    version: ServerApiVersion.v1,<br>    strict: true,<br>    deprecationErrors: true,<br>  }<br>});<br><br>async function run() {<br>  try {<br>    // Connect the client to the server (optional starting in v4.7)<br>    await client.connect();<br>    // Querying our database<br>    const cursor = await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).find();<br>    const array = await cursor.toArray()<br>    return array;<br>  } finally {<br>    // Ensures that the client will close when you finish/error<br>    await client.close();<br>  }<br>}<br><br>export default async function Database() {<br>    const greetings =  await run();<br>    return (&lt;&gt;<br>        {greetings.map(greetingObj=&gt; &lt;h1&gt;{greetingObj.greeting}&lt;/h1&gt;)}<br>    &lt;/&gt;)<br>  }<br></pre><p>Remember again to switch out the username and password.</p><p>Congratulations! Now you have got your own database, back end and front end connected all together and if you go to localhost:3000/database in your browser you should be able to see the “Hello World MongoDB” from the database on your screen. Well done! There are just a few things we need to adjust before we can push this code to GitHub. First of all we don’t want any sensitive information to be visible in our GitHub repository and that is why we move the uri line that includes our password to a .env variable. and make sure that in our .gitignore file .env is specified. We do this in our root folder like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zL257PU10zYaEs09luHDtw.gif" /><figcaption>The variable name should actually be MONGODB_URI but not MONGO_URI like in the video here above</figcaption></figure><p>Now we can switch out the string in the uri variable for our new environment variable. This could cause an error if the environment variable is undefined but we can catch that error in the next line. Also we should add a key prop to our &lt;h1&gt; element to help React organize the array. The _id from our database fits well to this because it should be unique and the id is always unique. We need to call the toString method on it because MongoDB gives us an object. After all this our code should look something like this:</p><pre>import { MongoClient, ServerApiVersion } from &#39;mongodb&#39;<br><br>    <br>const uri = process.env.MONGODB_URI<br>if(!uri){<br>    throw new Error(&quot;environment variable MONGODB_URI is not defined&quot;);<br>}<br><br>// Create a MongoClient with a MongoClientOptions object to set the Stable API version<br>const client = new MongoClient(uri, {<br>  serverApi: {<br>    version: ServerApiVersion.v1,<br>    strict: true,<br>    deprecationErrors: true,<br>  }<br>});<br><br>async function run() {<br>  try {<br>    // Connect the client to the server (optional starting in v4.7)<br>    await client.connect();<br>    // Querying our database<br>    const cursor = await client.db(&quot;test&quot;).collection(&quot;greetings&quot;).find();<br>    const array = await cursor.toArray()<br>    return array;<br>  } finally {<br>    // Ensures that the client will close when you finish/error<br>    await client.close();<br>  }<br><br>}<br>export default async function Database() {<br>    const greetings =  await run();<br>    return (&lt;&gt;<br>        {greetings.map(greetingObj=&gt; &lt;h1 key={greetingObj._id.toString()}&gt;{greetingObj.greeting}&lt;/h1&gt;)}<br>    &lt;/&gt;)<br>  }</pre><p>There are definitely some things that can still be done better in this code like moving the database logic into a different folder and adding some more greeting to our database to see them on our page, add styling, add more collections and so on or you could be adventurous and try to implement the crud operations after the MongoDB documentation <a href="https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/">here</a>. Please comment on this article if you did this tutorial and tell me how your experience of it was because I would love to update it and do it better if there are some steps where you might get stuck. Thank you!</p><p>I have written a continuing article about doing the CRUD operations (Create, Read, Update and Delete). So if you are interested in continuing this tutorial you can continue <a href="https://ellertsmarik.medium.com/json-api-using-next-js-13-and-mongodb-f45e8e61b031">here</a>.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4394872f5bb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-mongodb-and-next-js-stack-for-beginners-b4394872f5bb">The MongoDB and Next.js Stack for Beginners</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The PERN stack with Docker for beginners]]></title>
            <link>https://faun.pub/the-pern-stack-with-docker-for-beginners-9fa76e574d82?source=rss-8601d2548892------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fa76e574d82</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ellert Smári Kristbergsson]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 16:25:54 GMT</pubDate>
            <atom:updated>2022-03-06T21:14:48.976Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a tutorial that aims to be a step-by-step guide for how to implement the PERN stack with Docker. I have earlier made a tutorial about how to implement a MERN stack with MongoDB in the cloud and you can read about that one <a href="https://ellertsmarik.medium.com/the-mern-stack-for-beginners-e607eb8b7100">here</a>. These tutorials are made for students in <a href="https://en.tskoli.is/skoli/reykjavik-academy-of-web-development/">The Reykjavík Academy of Web Development</a> but everyone is welcome to use it for their needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ck0D1p7gdpHI-4iybAZv6Q.png" /></figure><h3>What is the PERN stack?</h3><p>The PERN stack is a technology stack for those who want to make websites. PERN stands for PostgreSQL, Express, React and NodeJS. In this tutorial we will explain how these tools are connected together to get you started using this stack. Other popular stacks are for example the LAMP stack, .NET or MERN.</p><h3>What is Docker?</h3><p>Docker is a technology to ensure the same functionality independent of what platform you are working on. As you might have noticed while working in groups, it can be hard to develop on many different machines. Often things don’t work the same on a Windows machine as on a Mac. This is where Docker comes in handy with containers that are a bit like small, light weight, virtual machines that you can run on your machine and push to the cloud where others can then get it and take over from there.</p><p>These machines (like most web servers) often use some version of Linux. As oppose to classical virtual machines, docker containers are very small and you can get them up and running in a short amount of time so it adds very little overhead to the usual pulling and pushing that you anyways need to do when you are working in groups.</p><h3>Before we start</h3><p>Before you can start you will need to make sure that NodeJS and yarn are installed on your system. You can do this by typing in the commands node --version if you see the letter v followed by some numbers separated by dots you have NodeJS installed. If not, you will need to install it first <a href="https://nodejs.org/en/">here</a>. After installing NodeJS you will have the default <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> called npm. In this tutorial I will be using a different package manager called yarn but it is easy to install it using npm by typing npm install -g yarn into the terminal. On some mac computers you might need to use sudo to install modules globally in that case you just add sudo in front like so: sudo npm install -g yarn. Also you will need to install docker. <a href="https://www.freecodecamp.org/news/the-docker-handbook/#how-to-install-docker">Here</a> are very good instructions on how to install docker to your computer. Notice that the guide has three different versions, one for each operating system. That would not be needed if you would already have docker.</p><h3>Docker</h3><p>Docker is a command line application like git so you will need to open up your terminal. You can, for example, use the CMD on a Windows machine, Terminal on a Mac, Bash on Linux or just let VScode decide for you by starting VScode and opening up a terminal there. When you have fired up the terminal you can finally officially start this tutorial by typing in docker --help and pressing enter. This will output a lot of text that shows all the commands that can be used with docker. Don’t worry, we won’t be using near all these commands. In this tutorial you will mostly be working with run and container.</p><p>The --help flag can be very helpful if you want to get to know more about the commands that you are typing into the terminal. This also applies to other command line applications, for example git, if you try git commit --help you will get some information about the git commit command and actually most terminal applications implement the --help flag so go ahead and use it as often as you can. Since we are going to be using the docker run command you can maybe guess what we are going to do next? …Yes you are right we are going to run the docker run --help command . The output is again pretty long but I would like you to pay special attention to the, --publish, --detatchand --env flags… Oh yeah, and be aware of the OOM Killer, he is dangerous.</p><h4>PostgreSQL with Docker</h4><p>Now you have everything you need to get started with docker and try out any development environment that you want. I understand that it can be hard to start so I will help you with your first command. Here is how you would get an instance of PosgreSQL running on your machine in only one command. Notice that you don’t even need to have PostgreSQL installed on your machine: docker run --env POSTGRES_PASSWORD=&lt;password&gt; --publish 5432:5432 --detach postgres .Notice that this needs to be all in one line when you put it to the terminal. Also replace the &lt;password&gt; part with your own password and remember the password because we will be using it later in this tutorial. If you get an error messages you might need to put sudo in front of the whole thing so it will become sudo docker run --env POSTGRES_PASSWORD=&lt;password&gt; --publish 5432:5432 --detach postgres . If this is the case you will probably always need to add sudo in front of the docker commands</p><p>Now let’s look at what exactly this command does:</p><ul><li>docker run is the command used to run docker containers on your machine. If it does not exist yet on your machine it will automatically search hub.docker.com for the image and download it from there</li><li>--env allows us to declare an (or a list of) environment variable in our container. In the <a href="https://hub.docker.com/_/postgres">documentation</a> for the PostgreSQL image it states that only one environment variable is required for creating this container ( POSTGRES_PASSWORD ) but there are many others that are optional and I encourage you to check them out there in the documentation. Notice that you should not type out the &lt;password&gt; part, but replace it with your own password</li><li>--publish connects a port in the container to a port on your computer and since PostgreSQL runs on port 5432 we use them here. If you want to use some other port for your database you can change the firstnumber into something else like --publish 3002:5432 would run PostgreSQL on port 3002 on your computer</li><li>--detach makes the container to run in the background so that we can continue to use our terminal for other commands as well</li><li>postgres is the name of the image and that is how docker will know that you want the container that runs PostgreSQL</li></ul><p>Now to make sure that your container is running you can run docker container ls and you should be able to see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*wBIYavZxsMPdfc9XwKxTCQ.png" /></figure><p>The line braking might be in different places and some numbers will be different. If you see this line you have a running PostgreSQL server on your machine. Congratulations!</p><p>Notice that docker gives our containers funny random names. My container is, for example, called nervous_shockley. Copy this name and store it somewhere because we will use it later in this tutorial. You can also choose a name for your container by adding the --name flag when you run the docker run command.</p><h4>PgAdmin with Docker</h4><p>Having a database running on our machine is not doing very much for us. We know that it exists because we can see the line in the terminal but we have no convenient way of interacting with it. We need something graphical like the Atlas pages for MongoDB. Thankfully there exists such peace of software and we can easily get it with only one line of command because we have Docker! This software is called PgAdmin and is exactly for making the interface to the database a bit more graphical.</p><p>The command we need for that is this (don’t run this command just yet, first read the explanation): docker run -p 8080:80 -e &#39;PGADMIN_DEFAULT_EMAIL=writeyour@email.here&#39; -e &#39;PGADMIN_DEFAULT_PASSWORD=writeYourPasswordHere&#39; -d dpage/pgadmin4 . Notice that now we use only one letter with one “-” in front of it, replacing the flags we used earlier. If you look at the output of the docker run --help command that we ran earlier you will notice that many of the flags have a shorter version that is only one letter, that is what we did there. Now here comes the explanation of the command:</p><ul><li>docker run is the same as before to run container from existing images (in the cloud or on our machine)</li><li>-p 8080:80 is the same as the --publish flag and because PgAdmin runs by default on port 80. Feel free to choose another port</li><li>-e is the same as --env . Now there are two of them and you should put your own e-mail and password there on the left side of the equal signs</li><li>-d is the same as --detach</li><li>dpage/pgadmin4 is the name of the image. Notice that now we have a “dpage/” before the name of the software and that is because this is not an official image provided by hub.docker.com but some guy that calls himself dpage on hub.docker.com. You can even see his picture if you look him up there. This image is very widely used, has more than 100 milion downloads and 877 stars as of this writing so it is pretty likely to be good. You can also create your own image for everyone to use and you should if you have a favorite stack because it is so easy to get people on board using your stack if it is easy to get it up and running but that is outside of the scope of this tutorial.</li></ul><p>Now one more thing before you run the command, as mentioned before you can use the --name flag to name your container. It will become something like --name myContainer . You can stuff that thing into the command before or after any of the other flags. We could for example put it in-between our -eflags like so (note that the command should all be in only one line): docker run -p 8080:80 -e &#39;PGADMIN_DEFAULT_EMAIL=writeyour@email.here&#39; --name myContainer -e &#39;PGADMIN_DEFAULT_PASSWORD=writeYourPasswordHere&#39; -d dpage/pgadmin4 . Now that you know that the order of the flags does not matter and you can compose them in whatever way suits you best you can press enter and see this beautiful command work its magic.</p><p>Now you should have a database and a graphical interface for it running on your computer. So you want to see the graphical interface? Ok, then, just go to your browser and type into the address bar “localhost:8080” (or change 8080 to whatever port you chose with our -p flag). Now you shouls see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwhXwpTs-aXm-AS3a12hhQ.png" /></figure><p>Now enter the email and password that you used when executing the command. If you don’t remember it you can press the “up arrow” on your keyboard until the command shows up and read it from there. Now you should see the dashboard. Here we can add the PostgreSQL server that we just acquired from docker earlier. Start by clicking the “Add New Server”, create a name for your server and then click connection like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d608xzBHV95yDsggSSP-Tw.png" /></figure><p>Now the gui is asking you for a Host name/address. Getting the IP address of our docker container requires some inspections and it just so happens that docker has a handy command called docker inspect . As you might recall from earlier in this tutorial my PostgreSQL container name is nervous_shockley so I would run docker inspect nervous_shockley in my terminal to get the information I need. If you don’t remember the name of your PostgreSQL container you can always run docker container ls again to find out, just make sure not to confuse it with your PgAdmin container.</p><p>When you run this command you will get huge amount of information displayed on your screen. Thankfully the IP address is on the bottom so you don’t need to scroll to be able to see it there. It will probably be 172.17.0.2 but you would better check it to be sure. If you can not find your IP address in the sea of information a handy tip (that you can always use in the terminal) is to pipe the command to grep like this docker inspect container_name | grep IPAddress . This will show you only the lines with IPAddress. This can be very handy when you are working with large outputs in the terminal, for example with log files.</p><p>Now that you have your containers IP address just write it into the “Host name/address” filed on the PgAdmin site, write postgres into the “username” field and the password you chose when creating the PostgreSQL container into the password field and click “Save” like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*X5UGEmA48v5lA69bgW4ihg.png" /></figure><p>Now you should be able to see some graphs monitoring your database.</p><p>The next thing to do here is to create a table in this new database. This can be done by selecting our new database in the PgAdmin page, expanding schemas, right clicking on tables and select Create -&gt; Table… Then you can name your table what you want. I will name it devices to have similarity to what we did in the MongoDB tutorial like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LXfNQD8C_rXyolYdK_rGA.png" /></figure><p>Now that we have a table we should create a column to that table. That column will be our greeting. You will need to give it a name in the General tab and a definition stating the data type in the Definition tab like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*vKx6xdz4VvvUi3vKX2hZRw.png" /></figure><p>We use <strong>character varying</strong> (that basically means a string) since our data will consist of varying characters (a greeting). Now create another column called ID that has the data type <strong>serial</strong>. In relational databases all tables should have a primary key column. In most cases this column is called ID and is just a number starting at 1, increasing by 1 with every row added (that is called serial in PostgreSQL). Next up we have the final touch, to put the greeting into the database and that can be done through the PgAdmin by adding a primary key constraints and editing the table in the gui like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*pBeYpSEydpss974X4KbSEg.png" /><figcaption>This picture is taken from an <a href="https://stackoverflow.com/a/45526433/3456542">answer in StackOverflow</a> by cm1 and Shady Mohamed Sherif</figcaption></figure><p>Alright! Now that we have got our data into our database it is time to do very similar things to what we did when we were dealing with MongoDB, namely adding an Node-Express API and connecting the React front-end to it.</p><h3>Making the server</h3><p>Let’s start by opening up VScode in an empty directory. I do this by opening the directory in my terminal and writing code . . From there I open the terminal and run the commandyarn init --yes . This will initialize a new NodeJS project in our directory. When I run a command I type it in the terminal like shown below. In the future I will just state that I run a command and this is what I mean by that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HGvg0kmB014hqfNI.gif" /></figure><p>If you see a package.json file in your directory that means that the command has ran successfully. If not you might want to try to run it again. Now let’s practice commands in the terminal. If you run the command yarn add express you will see that something is installed and if you open the package.json file you should see a line like this &quot;express&quot;: &quot;^4.17.1&quot; . This means that Express has been successfully installed. This is how simple it is to install new modules with yarn.</p><p>Next I create a new file called server.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HbfO4Z41YOZVwzHM.gif" /></figure><p>You will also need to change the value of “main” in package.json from “index.js” to “server.js”. In this server.js file we will write all the code that belongs to the server (NodeJS will run this file with the code we write for PostgreSQL and Express).</p><h3>Express — Hello World:</h3><p>Let’s start by creating a Hello World application in Express (see code below). Now that we have it installed we just need to require it in our server.js file, listen to a port and listen to a get request. If we want to allow the front-end to access our api with fetch we need to allow that too. We can do this by installing a simple middleware module for Express called <a href="https://expressjs.com/en/resources/middleware/cors.html">cors</a> and use it.</p><p>Finally we run the command node server.js in the terminal And this is what it all looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771bb17fd2c0e979fd52075a86f0ca7b/href">https://medium.com/media/771bb17fd2c0e979fd52075a86f0ca7b/href</a></iframe><p>Now that we have our server running we should be able to go to this link and see our hello world: <a href="http://localhost:5001/">http://localhost:5001</a> . If you see a “Hello World!” when you visit the link you have done everything correctly and you have made an Express app, congratulations!</p><p>Now that Express is ready we just need a small adjustment to the code and then we are ready to go! We need to add two dependencies to our app (using yarn add). These are pg (a way for Node to talk to PostgreSQL) and dotenv (a way to define environment variables that PostgreSQL uses a lot). We will require dotenv in our app but we don’t need to store it in a variable since we only want to call it’s config function that enables us to define these variables. This is how it looks like in our code: require(&#39;dotenv&#39;).config() .</p><p>The pg dependency is also a bit special since we will want to de-structure the object that it returns: const { Client } = require(&#39;pg&#39;) this is the same as const pg = require(&#39;pg&#39;) and const Client = pg.client . Now that we have our dependencies, let’s focus on what we need to do inside our app.get function (the function that runs every time someone visits our page). The first thing we will need to do is to add the async keyword in front of the callback function like this app.get(&#39;/&#39;, async (req, res)=&gt;{ . Then inside the function we can take out the res.send(&quot;hello world&quot;) and replace it with the greeting from PostgreSQL. We will need to create a new client instance like this const client = new Client() and then we will need to connect it to the database like this await client.connect() . Now that we are connected we can finally get the data from the database. Let’s store it in a variable we call data like this: const data = await client.query(&#39;SELECT * FROM devices&#39;) . The string we pass to the client.query function is called SQL code. Please check out all the things you can do with SQL <a href="https://sqlbolt.com/">here</a> it is a wonder in it self. Now the last two lines inside app.get are for sending the data to the client: res.send(data.rows) and closing the connection to the database: await client.end()</p><p>After everything the server.js file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b4f0c64eb4d87ae529324badc09d4ab/href">https://medium.com/media/6b4f0c64eb4d87ae529324badc09d4ab/href</a></iframe><p>But wait what??? How does server.js know about our PostgreSQL database? What kind of black magic is this? … Well actually that is where the environment variables come in (line 5 you remember?). We need to create one more file called .env in the same directory as our server.js. In that file you will put these lines:</p><pre>PGHOST=localhost<br>PGUSER=postgres<br>PGDATABASE=postgres<br>PGPASSWORD=ThePasswordYouUsedForThePostgreSQLContainer<br>PGPORT=5432</pre><p>There are loads of other variables that you can define in there and you can read all about them <a href="https://www.postgresql.org/docs/9.3/libpq-envars.html">here</a>. IMPORTANT: Remember to create also a .gitignore file and add .env to that file so that you are not pushing your password into GitHub. It is also good to have node_modules in there so you are not pushing it. Now you can put all your secrets into environment variables and you wont need to worry about it being exposed even if your code is open source. It is also a good idea to store the local url in an environment variable since often you will want to use localhost when developing locally while the web-server hosting your page will probably use something that is hosted publicly.</p><p>Now you should be able to run your server and go to localhost:5001 in your browser and see the greeting that you wrote in your database.</p><h3>Connecting React:</h3><p>Now that we have the back end up and running we can just go a head and create a totally new project for ourselves in a completely new directory. It could even be stored on a different computer but in this tutorial we will assume that it is stored on the same computer. It is simple to start a new react app. Just open up a <strong>new</strong> terminal (it is important to keep the other terminal running so that the React app can connect to it) in the directory you want to have your project ( remember that it will create a new directory so you will probably not want to be in an empty directory when you create the app). Now we just follow the instruction given by the <a href="https://github.com/facebook/create-react-app#create-react-app--">create-react-app</a> project:<br>write npx create-react-app mern-app to create the app and then open the new directory by typing cd mern-app now you can write code . if you want to open up the project in VScode. Next type yarn start to start the app. Now you can navigate to your App.js like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rXsPS6gVqCeuh71N.gif" /></figure><p>As you can see there is some code there already but we can just take it out and leave the App.js file looking like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/090d0488c7a8766544512cd72695bc68/href">https://medium.com/media/090d0488c7a8766544512cd72695bc68/href</a></iframe><p>But now we want to get the “Hello World MongoDB” from our database and display it there in place of “Hello World React!”. For this we will need to import two things from react, namely the useState and useEffect hooks ( you can read more about React hooks <a href="https://reactjs.org/docs/hooks-intro.html">here</a> ) . Then we will need to use the hooks accordingly. After adding all this to our code it will look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6e8b201a9ae132672c6480e720f5b12/href">https://medium.com/media/a6e8b201a9ae132672c6480e720f5b12/href</a></iframe><p>Tada! we have got the data from PostgreSQL, through Node.js and Express all the way to our front end in React. Congratulations on finishing this tutorial and having a full PERN stack! Notice how the React code is exactly the same in MERN as in PERN. This is why it can be so handy to devide the team into fron-end developers and back-end developers because the front end code can look exaxtly the same even though we are using two copletely different databases to aquire this result</p><h3>Final words:</h3><p>This is a good way to get started but there is a whole lot more to explore. To continue from here I recommend you to tinker a little bit with the code. Try to add more rows to the table, add more tables with different kind of data etc. When you feel that you are familiar with how the code works a good next step would be to read some documentation. You could start with <a href="https://sqlbolt.com/">SQL</a> or <a href="https://expressjs.com/en/4x/api.html#app">Express</a> or <a href="https://reactjs.org/docs/react-api.html">React</a> or even <a href="https://nodejs.org/docs/latest/api/">NodeJS</a> and try out some new functions and methods. There are also loads of other tutorials out there who teach how to do specific things with the PERN stack. This is just the start of a huge world of opportunities and things to create…</p><p>If you get stuck on any of the steps of this tutorial please let me know so that I can fix it and make it better. Also if you spot some errors I would be very thankful if you let me know so that I can fix them.</p><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fa76e574d82" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/the-pern-stack-with-docker-for-beginners-9fa76e574d82">The PERN stack with Docker for beginners</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The MERN stack for beginners]]></title>
            <link>https://faun.pub/the-mern-stack-for-beginners-e607eb8b7100?source=rss-8601d2548892------2</link>
            <guid isPermaLink="false">https://medium.com/p/e607eb8b7100</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Ellert Smári Kristbergsson]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 14:22:35 GMT</pubDate>
            <atom:updated>2024-01-08T15:20:45.637Z</atom:updated>
            <content:encoded><![CDATA[<p>Here I will attempt to explain step-by-step, how to set up a MERN stack. This article is made for students in the <a href="https://en.tskoli.is/skoli/reykjavik-academy-of-web-development/">Reykjavík Aca­demy of Web <br>Develop­ment</a> but of course everybody is welcome to read it and use it as a source for their own projects. If you get stuck on any of the steps of this tutorial please let me know so that I can fix it and make it better .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJlV4R3_D9wQpNq6daQYbg.jpeg" /></figure><h3>What is the MERN stack?</h3><p>The MERN stack is a technology stack for people who want to make a web application. MERN stands for <a href="https://www.mongodb.com/">MongoDB</a>, <a href="https://expressjs.com/">Express</a>, <a href="https://reactjs.org/">React</a> and <a href="https://nodejs.org/en/">NodeJS</a>. If you are using these technologies you are using the MERN stack. I will be using some other tools as well in this tutorial like VScode and Firefox but they are not a part of the stack. MERN is just one of many stacks that you can choose from when you are starting to develop your own web. It is particularly handy for people who like to be able to use JavaScript everywhere in their code base. Other popular stacks are for example the <a href="https://en.wikipedia.org/wiki/LAMP_(software_bundle)">LAMP</a> stack or <a href="https://dotnet.microsoft.com/">.NET</a></p><h3>Before we start</h3><p>Before you can start you will need to make sure that NodeJS and yarn are installed on your system. You can do this by typing in the commands node --version if you see the letter v followed by some numbers separated by dots you have NodeJS installed if not, you will need to install it first <a href="https://nodejs.org/en/">here</a>. After installing NodeJS you will have the default <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> called npm. In this tutorial I will be using a different package manager called yarn but it is easy to install it using npm by typing npm install -g yarn into the terminal. If you are on a Mac computer you will probably need to do sudo before likesudo npm install -g yarn .</p><h3>Diving into it</h3><p>Let’s start by opening up VScode in an empty directory. I do this by opening the directory in my terminal and writing code . . From there I open the terminal and run the commandyarn init --yes . This will initialize a new NodeJS project in our directory. When I run a command I type it in the terminal like shown below. In the future I will just state that I run a command and this is what I mean by that:</p><figure><img alt="executing the yarn init — yes command in VScode" src="https://cdn-images-1.medium.com/max/1024/1*e39pnP0B8CcHokJAHcIunQ.gif" /></figure><p>If you see a package.json file in your directory that means that the command has ran successfully. If not you might want to try to run it again. Now let’s practice commands in the terminal. If you run the command yarn add express ( If you get an error it might be because the name of your project includes spaces ). You can change this in package.json. If everything goes as planned, you should see that something is installed and if you open the package.json file you should see a line like this &quot;express&quot;: &quot;^4.17.1&quot;. This means that Express has been successfully installed. This is how simple it is to install new modules with yarn.</p><p>Next I create a new file called server.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5ehGT7v9oCo_6HqE7Sadg.gif" /></figure><p>In this server.js file we will write all the code that belongs to the server (NodeJS will run this file with the code we write for MongoDB and Express).</p><h3>Express — Hello World:</h3><p>Let’s start by creating a Hello World application in Express (see code below). Now that we have it installed we just need to require it in our server.js file, listen to a port and listen to a get request. If we want to allow the front-end to access our api with fetch we need to allow that too. We can do this by installing a simple middleware module for Express called <a href="https://expressjs.com/en/resources/middleware/cors.html">cors</a> by writing yarn add cors and use it.</p><p>Finally we run the command node server.js in the terminal And this is what it all looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsZeeTwZk6RtRUpjXImDIQ.png" /></figure><p>And here is the code so that you can copy it if you want:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24eff86f400d62d32df80de2e20e10c5/href">https://medium.com/media/24eff86f400d62d32df80de2e20e10c5/href</a></iframe><p>From now on I will not take screenshots of VScode but rather post the code like this so that you can copy it from here.</p><p>Now that we have our server running we should be able to go to this link and see our hello world: <a href="http://localhost:5000/">http://localhost:500</a>1 . If you see a “Hello World!” when you visit the link you have done everything correctly and you have made an Express app, congratulations!</p><h3>MongoDB — Hello World:</h3><p>Our next step here is to create a database and since we are using the MERN stack our choice is MongoDB. The simplest way to set up such a database is to go sign up for the free cloud database at <a href="https://www.mongodb.com/cloud/atlas/signup">MongoDB Atlas</a>.</p><p>The First time you sign up there you will be asked to go through a few steps to set up your account. In one step you are asked to choose your preferred programming language and there you can choose JavaScript. Other than that you can write/choose what ever you want.</p><p>Once you have done that you will arrive to a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GRo0syWD8uy6aD4N.png" /></figure><p>Select the areas marked with red circles. Select a username and password and click Create User. To get the IP Address that you need to put into the IP Address field at the bottom, you can google “what is my ip” and it will show you something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QQaWxvV5hojtGUj1.png" /></figure><p>When you have entered your IP Address and given it a name in the description (if you are at home a good idea would be to put “home” in the description, if you are at school you can put “shcool”) and clicked the “Add Entry” button you should see the IP Address there below. If you see it there you can continue by clicking the “Finish and Continue” button in the lower, right corner. You will get a pop-up window where you can click “Go To Database” where you will be greeted with this window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D04QHEW93rPu00_k4g1R2A.png" /></figure><p>There you will be presented with five options, choose the one on the top with the title “Connect your application”. Now you will be presented with instructions on how to connect the database to your application. If you tick into the box next to “Include full driver code example” you will be able to copy exactly the code that you need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*6wKkA0Ld-W4OzTfANmfm8g.png" /></figure><p>Now that we have the code we paste it into our server.js file after the line where it says const PORT = 5001; . The next step is to replace the part in our code where it says “&lt;password&gt;” and write your own MongoDB Atlas password there. Now there is still one more thing we need to to before we can go on and create our database and that is to install the mongodb module. But as mentioned earlier installing a new module is an easy task. Simply type yarn add mongodb in your terminal (you might need to stop the server first but that is done by holding in the “Ctrl” key on your keyboard and pressing “c” at the same time). To make sure that the module has been installed you can check your package.json file and see if you can find it there. If it is not there you should try again.</p><p>Now let’s turn back to the MongoDB Atlas page. If you close the modal you will get back to the page where we started. This time we want to select the Database option on from the sidebar and click the Browse Collections button from there. This will take us to a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heHopgwiwEAW3thjEQVRVQ.png" /></figure><p>You will get a pop-up offering you to use demo data or add your own. Since we are trying to learn how to make our own database you should click “Add My Own Data”. Now let’s name the database <strong>test</strong> and the collection <strong>greetings</strong> and click the green button that says “create”. Now the database will appear in the list on the left. You can open it by pressing the small gray arrow in front of it’s name (greetings) like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*WeRYaJaGnmfrEo4J.png" /></figure><p>Now if you click “devices” you will get up the view that we can see here above. Now let’s add two documents to the collection by clicking the “INSERT DOCUMENT” button that you can see there on the right side. You will get a modal looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Y1rcfDj4HCAKSrYH.png" /></figure><p>There will be and _id property already filled in by default but then we can add more properties. Let’s add one called greeting that holds the value “Hello World MongoDB” like you can see above and then press the green button that says “Insert”.</p><p>If you have moved your server (in this case your computer) from one house to another (for example to the school) you will need this step:</p><p><em>Allow the ip address from our server. In this case it is probably just your own computer. Then we can click the “Network Access” in navbar on the left shown with a red circle on the picture here below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbWClP1AHCTLORyIwVDofw.png" /></figure><p><em>And then you click the green button there in the middle. After that you can click the “ADD CURRENT IP ADDRESS” and then the green button in the lower right corner where it says “Confirm”.</em></p><p>Now that you have all your settings ready we just need a small adjustment to the code and then we are ready to go! Let’s open our server.js file and move the client.connect function into the app.get function. We will need to add the async keyword in front of the function inside the client connect function like this client.connect(async err =&gt; { . Then we will fill in the required things below the comment that says: “perform actions on the collection object”. There are actually only two lines that we need to add. In the first line we will get the data from our collection (the “Hello World MongoDB” from the “devices” collection). The line will look like this const data = await collection.find().toArray(); . The find() method is the way to get data from MongoDB we can get all the data available by passing no arguments to the find function. MongoDB will return an object that looks a bit like an array but it is not a real array and that is why we turn it into an array by calling toArray().</p><p>Now to finalize it we just erase the client.close() because we don’t want to close the database each time someone comes to visit our page. Then we also want to erase the res.send(&quot;Hello World!&quot;) line and call res.send(JSON.stringify(data)) from within our client.connect function. This is now possible because we moved the client.connect function inside app.get and from there we have access to the res object. As we recall that data is an array and since we can only send strings between client and server we need to turn it into a string first by calling JSON.stringify. If you now write node server.js in your terminal and then go to <a href="http://localhost:5000/">http://localhost:500</a>1 you should see there the data coming from the database along with the message “Hello World MongoDB!”</p><p>After all this the code in server.js should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd163606c5736b7664f8bfe4760198c/href">https://medium.com/media/cfd163606c5736b7664f8bfe4760198c/href</a></iframe><p>Congratulations! Now you have got the M, E and N from the MERN stack. From here you could still decide to go with the MEAN stack and use Angular in the front end or even the MEVN stack and use Vue.js. But we are going to use React to finalize this tutorial.</p><h3>React — Hello World:</h3><p>Now that we have the back end up and running we can just go a head and create a totally new project for ourselves in a completely new directory. It could even be stored on a different computer but in this tutorial we will assume that it is stored on the same computer. It is simple to start a new react app. Just open up a <strong>new</strong> terminal (it is important to keep the other terminal running so that the React app can connect to it) in the directory you want to have your project ( remember that it will create a new directory so you will probably not want to be in an empty directory when you create the app). Now we just follow the instruction given by the <a href="https://github.com/facebook/create-react-app#create-react-app--">create-react-app</a> project:<br>write npx create-react-app mern-app to create the app and then open the new directory by typing cd mern-app now you can write code . if you want to open up the project in VScode. Next type yarn start to start the app. Now you can navigate to your App.js like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KC_6Aewup81VzMqV47Z_1g.gif" /></figure><p>As you can see there is some code there already but we can just take it out and leave the App.js file looking like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2966d79b6c727556e7f534c71ffa343/href">https://medium.com/media/a2966d79b6c727556e7f534c71ffa343/href</a></iframe><p>But now we want to get the “Hello World MongoDB” from our database and display it there in place of “Hello World React!”. For this we will need to import two things from react, namely the useState and useEffect hooks ( you can read more about React hooks <a href="https://reactjs.org/docs/hooks-intro.html">here</a> ) . Then we will need to use the hooks accordingly. After adding all this to our code it will look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca6eec2e577410f040a8f64cbc84e86b/href">https://medium.com/media/ca6eec2e577410f040a8f64cbc84e86b/href</a></iframe><p>Tada! we have got the data from MongoDB, through Node.js and Express all the way to our front end in React. Congratulations on finishing this tutorial and having a full MERN stack!</p><h3>Final words:</h3><p>This is a good way to get started but there is a whole lot more to explore. To continue from here I recommend you to tinker a little bit with the code. Try to add a new collection, add more documents to the collection etc. When you feel that you are familiar with how the code works a good next step would be to read some documentation. You could start with <a href="http://mongodb.github.io/node-mongodb-native/3.6/api/">MongoDB</a> or <a href="https://expressjs.com/en/4x/api.html#app">Express</a> or <a href="https://reactjs.org/docs/react-api.html">React</a> or even <a href="https://nodejs.org/docs/latest/api/">NodeJS</a> and try out some new functions and methods. There are also loads of other tutorials out there who teach how to do specific things with the MERN stack. This is just the start of a huge world of opportunities and things to create…</p><p>If you get stuck on any of the steps of this tutorial please let me know so that I can fix it and make it better. Also if you spot some errors I would be very thankful if you let me know so that I can fix them.</p><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e607eb8b7100" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/the-mern-stack-for-beginners-e607eb8b7100">The MERN stack for beginners</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>