<?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 unaGata on Medium]]></title>
        <description><![CDATA[Stories by unaGata on Medium]]></description>
        <link>https://medium.com/@fallen.snitch?source=rss-d451829051d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*plrUtE4iVHGhakjA</url>
            <title>Stories by unaGata on Medium</title>
            <link>https://medium.com/@fallen.snitch?source=rss-d451829051d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fallen.snitch/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[Stop Paying for SSL: FREE HTTPS with Docker, Nginx & Certbot (Auto-Renew)]]></title>
            <link>https://medium.com/@fallen.snitch/stop-paying-for-ssl-free-https-with-docker-nginx-certbot-auto-renew-33a6a20affc8?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/33a6a20affc8</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[httpscertificate]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[lets-encrypt]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 16:10:59 GMT</pubDate>
            <atom:updated>2026-07-20T16:10:59.646Z</atom:updated>
            <content:encoded><![CDATA[<p>So, you finally deployed your application to a Virtual Machine, like Google Compute Engine, AWS EC2, or an Ubuntu VPS. You type in your domain name, hit enter, and… your browser screams at you with a massive red <strong>“Your connection is not private”</strong> or <strong>“Not Secure”</strong> warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzKT3mUae-FM4OBrMHTt3Q.jpeg" /></figure><p>Buying an SSL certificate can be expensive and manually updating it is annoying.</p><p>In this guide, I will show you how to get a completely FREE SSL certificate using Let’s Encrypt, connect it to your Docker Compose setup with Nginx, and most importantly — automate the renewal process using Cron so you never have to think about it again. Let’s dive in!</p><h3>The Architecture: How It Works</h3><p>First, make sure you have a domain name and that its A-record is pointing to the IP address of your server.</p><p>If you like video version more click <a href="https://youtu.be/-LeVoGLqRmg?si=O8UYjm2Uzb3hz6gt">here</a>.</p><p>Here is how our architecture will work: We will have an Nginx container and a Certbot container. They need to talk to each other to verify your domain and share the certificates. We will achieve this by sharing volumes in our Docker Compose setup.</p><h3>Step 1: Nginx &amp; Docker Compose Setup</h3><p>We need to set up a “magic bridge” between Nginx and Certbot so Certbot can place the generated certificates exactly where Nginx expects them.</p><p>Here is our basic nginx.conf. For now, it only listens on port 80 to catch the Let&#39;s Encrypt challenge:</p><pre>server {<br>    listen 80;<br>    server_name yourdomain.com www.yourdomain.com;<br><br>    location /.well-known/acme-challenge/ {<br>        root /var/www/certbot;<br>    }<br>}</pre><p>And here is the docker-compose.yml. Pay close attention to the volumes section:</p><pre><br>services:<br>  nginx:<br>    image: nginx:alpine<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/conf.d/default.conf<br>      - ./certbot/conf:/etc/letsencrypt<br>      - ./certbot/www:/var/www/certbot<br><br>  certbot:<br>    image: certbot/certbot<br>    volumes:<br>      - ./certbot/conf:/etc/letsencrypt<br>      - ./certbot/www:/var/www/certbot</pre><p>Both Nginx and Certbot are mounting ./certbot/conf and ./certbot/www. This is crucial for the verification process.</p><p>If you want to support me or just say thank you I will be very gratefull for your support here: <a href="https://buymeacoffee.com/soyunagata">https://buymeacoffee.com/soyunagata</a></p><h3>Step 2: Generating the Certificate</h3><p>Now, we need to run Certbot to get our initial certificate. Run the following command in your server’s terminal:</p><pre>docker compose run --rm certbot certonly --webroot --webroot-path /var/www/certbot/ -d yourdomain.com -d www.yourdomain.com -m your@email.com --agree-tos --no-eff-email</pre><p>Once the command runs successfully, you’ll see a congratulation message. Our certificates are ready! Now, you just need to update your nginx.conf to listen on port 443 and enable SSL (using the newly generated certificates in /etc/letsencrypt/live/...).</p><h3>Step 3: Automating Renewals with Cron (The Magic)</h3><p>Here is the catch: Let’s Encrypt certificates expire every 90 days. If you forget to renew them, your site will go down. Let’s automate this so you can sleep peacefully.</p><p>In your server terminal, type:</p><pre>crontab -e</pre><p>We are going to add one simple line at the bottom of the file:</p><pre>0 3 1 * * cd /path/to/your/project &amp;&amp; docker compose run --rm certbot renew &amp;&amp; docker compose exec nginx nginx -s reload</pre><p>This tells the server to run the Docker Certbot renewal command on the 1st day of every month at 3 AM, and then immediately reload Nginx to apply the new certificates.</p><p>Save and exit. That’s it!</p><h3>Conclusion</h3><p>If you refresh your page now, that ugly red warning is gone, replaced by a beautiful, secure padlock: <strong>“Connection is secure”</strong>.</p><p>You now have a production-ready, fully automated HTTPS setup completely for free.</p><p>If this guide saved you a headache, don’t forget to clap 👏 and follow me for more real-world coding and deployment tips. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33a6a20affc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Lock Down Your Nginx Staging Like a Pro: 3 Proven Methods]]></title>
            <link>https://medium.com/@fallen.snitch/how-to-lock-down-your-nginx-staging-like-a-pro-3-proven-methods-1f2fa94a9ae2?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2fa94a9ae2</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[server-administration]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 15:33:03 GMT</pubDate>
            <atom:updated>2026-07-20T15:33:03.996Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve been sweating over a new project for a month, you finally push it to a staging server for some testing, and — boom — the next morning Google has indexed your half-baked “raw” version instead of the live site. Or even worse: your client finds those nasty bugs before you even had a chance to fix them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Qc-8GYEANF8uY0w3YfrRA.jpeg" /></figure><p>Today, I’m going to show you how to hide your dirty laundry from prying eyes using Nginx. If you like video version more click <a href="https://youtu.be/fyTcOh9-6Z0?si=9lp63HJoN90jctJL">here</a>.</p><p>A quick heads-up: this guide is for when you’re deploying on a standard Virtual Machine (VM). If you’re using AWS, Azure, or similar clouds, they have their own fancy tools for this. But for the rest of us — here are three ways to do it right.</p><h3>Method 1: Basic Authentication</h3><p>This method makes sure every uninvited guest gets a login popup right in their face.</p><p>To make this work, you need to add the auth_basic directive to your config and point it to a password file. But for Nginx to understand your super-secure password, it needs to be hashed and stored in a special file, usually called .htpasswd.</p><p>We have two paths here.</p><p><strong>Path 1: For the Docker Samurai.</strong> If you have no goal, only a path, you use Docker. Why bloat your server with extra packages when we can spin up an entire container just for one line of hash? Here’s the command:</p><pre>docker run --rm httpd:alpine htpasswd -nb myuser mypassword &gt; .htpasswd</pre><blockquote><strong><em>Pro tip:</em></strong><em> The utility runs inside a temporary container, but thanks to the redirect arrow (</em><em>&gt;), the ready-to-use </em><em>.htpasswd file will be created right on your server in your current directory. Just don&#39;t forget to manually move it to </em><em>/etc/nginx/ later.</em></blockquote><p>If you want to support me or just say thank you I will be very gratefull for your support here: <a href="https://buymeacoffee.com/soyunagata">https://buymeacoffee.com/soyunagata</a></p><p><strong>Path 2: For Normal Human Beings.</strong> If you don’t want to dance with tambourines, just install the utility directly on the server. For Ubuntu/Debian, it’s:</p><pre>sudo apt install apache2-utils</pre><p>And then generate the file exactly where it belongs:</p><pre>sudo htpasswd -c /etc/nginx/.htpasswd myuser</pre><p>The system will ask you to enter the password twice, and you’re good to go!</p><p>Next, go to your Nginx virtual host config and add these two lines inside the location block:</p><pre>server {<br>    listen 80;<br>    server_name stage.example.com;<br><br>    location / {<br>        auth_basic &quot;Administrator&#39;s Area&quot;;  # Title shown in browser<br>        <br>        # Path to our password file<br>        auth_basic_user_file /etc/nginx/.htpasswd;<br><br>        # ... your standard proxy settings here<br>    }<br>}</pre><p>Check the config for errors: sudo nginx -t. If everything is okay, reload Nginx: sudo service nginx reload.</p><h3>Method 2: IP Whitelisting</h3><p>I like to call this the “Closed Window.” This is perfect if your team has a static IP in the office or you’re using a corporate VPN. No passwords involved.</p><p>We’re using the allow and deny directives like this:</p><pre>server {<br>    listen 80;<br>    server_name stage.example.com;<br><br>    location / {<br>        # Allow a specific IP (e.g., your office)<br>        allow 192.168.1.100; <br>        <br>        # Allow an entire subnet (e.g., for your VPN)<br>        allow 10.0.0.0/24;   <br>        <br>        # Block everyone else (they get a 403 Forbidden)<br>        deny all;            <br><br>        # ... other config<br>    }<br>}</pre><p><strong>Crucial rule:</strong> Don’t you dare think you can place these lines randomly. Nginx reads these rules strictly top to bottom. So, write all your allow rules first, and put deny all at the very end.</p><h3>Method 3: The Combo (IP + Password)</h3><p>So, your company is huge — basically Amazon 2.0 — and you’ve got an international team where half the people are in the office and the other half are working from home?</p><p>Honestly, if you’re that big, your DevOps should’ve handled this already… but since you’re sitting here wasting work hours reading this guide, here is how you build a hybrid setup.</p><p>The magic directive here is satisfy any;. It tells Nginx: <em>&quot;Let the user in if AT LEAST ONE condition is met.&quot;</em></p><pre>server {<br>    listen 80;<br>    server_name stage.example.com;<br><br>    location / {<br>        # Logic: &quot;Either this OR that&quot;<br>        satisfy any;<br><br>        # Condition 1: IP Check<br>        allow 192.168.1.100; # Office folks get in without questions<br>        deny all;            # Others move to the second check<br><br>        # Condition 2: Basic Auth<br>        auth_basic &quot;Restricted Access&quot;;<br>        auth_basic_user_file /etc/nginx/.htpasswd; # Remote folks need a password<br><br>        # ... other config<br>    }<br>}</pre><h3>Conclusion</h3><p>I usually stick with method number one, but you should use whatever fits your team’s workflow best. Just don’t leave your staging server open to the world.</p><p>Don’t be a cheapskate with the claps at the end 👏. And if you’re not feeling too lazy, drop a comment and tell me how you secure your own staging servers. See ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2fa94a9ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Custom Shopify Embed App: App Bridge & CSP Headers Explained]]></title>
            <link>https://medium.com/@fallen.snitch/how-to-build-a-custom-shopify-embed-app-app-bridge-csp-headers-explained-8db0455698ab?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8db0455698ab</guid>
            <category><![CDATA[shopify-apps]]></category>
            <category><![CDATA[custom-shopify-app]]></category>
            <category><![CDATA[shopify-app-development]]></category>
            <category><![CDATA[shopify-web-development]]></category>
            <category><![CDATA[shopify-embed-app]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Thu, 14 May 2026 08:09:34 GMT</pubDate>
            <atom:updated>2026-05-14T08:09:34.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuwUThXM3_eOsMgYmAIrEA.jpeg" /></figure><p><em>Too lazy to read? I get it, my eyes would bleed too. </em><a href="https://youtu.be/wf7XaWbiR8o?si=k7FpvPZ7nmzhuM_E"><em>Watch the full video version on my YouTube channel here</em></a><em>, where I suffer through this so you don’t have to.</em></p><p>If you’re reading this, you probably need to build a Shopify Embed App, and you’re already tired of navigating their endless documentation. Let’s skip the fluff and get straight to the point.</p><p>We will assume you’re already registered as a Shopify Partner. Let’s break down the process using a real-world scenario: building a custom app to track orders and send custom client emails.</p><h3>Step 1: Deployment &amp; Local Testing</h3><p>Shopify doesn’t care where your app lives (a VM or a PaaS), but it <strong>must</strong> be served over HTTPS.</p><ul><li><strong>Local tip 📝:</strong> While developing, use <strong>ngrok</strong> to tunnel your local server and catch Shopify webhooks.</li></ul><p>Once your app is ready and you have your HTTPS URL, head to the Partners Dashboard.</p><h3>Step 2: App Configuration</h3><p>Click <strong>Create App -&gt; Create app manually</strong>. We are taking the manual route to maintain full control over the stack.</p><ul><li><strong>App URL</strong>: The home base of your app.</li><li><strong>Allowed redirection URL</strong>: Your OAuth callback URL. <em>Don’t mess this up, or you’ll be stuck with 401 errors.</em></li><li><strong>Scopes</strong>: Define your permissions here (e.g., read_orders).</li></ul><h3>Step 3: Secure Your Credentials</h3><p>Once saved, Shopify will generate a <strong>Client ID</strong> and a <strong>Client Secret</strong>. This is your app’s passport. Store them immediately in your .env file and never expose them.</p><h3>Step 4: Distribution Method</h3><p>Your app is useless until you define how it will be distributed. Go to the <strong>Distribution</strong> tab. If you are building this for a specific client, choose <strong>Custom Distribution</strong>. Enter the client’s store domain ([admin.shopify.com/store/shop](https://admin.shopify.com/store/shop)) and hit <strong>Generate Link</strong>. This is the installation link you&#39;ll use later.</p><h3>Step 5: Embed &amp; CSP Headers (Fixing the White Screen)</h3><p>Here is where most developers catch a white screen.</p><p>Your app renders as an iframe inside Shopify admin. Because modern browsers block third-party iframes by default, you must configure <strong>Content Security Policy (CSP)</strong> headers.</p><p>I built this backend on Symfony, so here is the EventSubscriber logic to tell the browser to allow Shopify to display your content:</p><pre>$shop = $request-&gt;query-&gt;get(&#39;shop&#39;);<br>$allowedUrl = $shop ? &quot;https://$shop&quot; : &quot;https://*.myshopify.com&quot;;<br>$response-&gt;headers-&gt;set(&#39;Content-Security-Policy&#39;, &quot;frame-ancestors $allowedUrl https://admin.shopify.com;&quot;);</pre><p><em>Note: Third-party cookies are dead. You must rely on Shopify Session Tokens to authorize requests, otherwise Safari (and soon Chrome) will block your app.</em></p><h3>Step 6: Webhooks</h3><p>To avoid constantly polling Shopify’s API, register a webhook (e.g., orders/create) pointing to your Redirection URL. Now, Shopify will proactively send a POST request to your backend the moment an order is created.</p><h3>Step 7: The OAuth Flow</h3><p>When a user clicks “Install”, Shopify hits your server with parameters. Your backend must:</p><ol><li><strong>Verify the HMAC signature</strong> to guarantee the request actually came from Shopify.</li><li>Exchange the temporary code for an <strong>Access Token</strong>.</li><li><strong>Save the Access Token in your database.</strong> The database is your app’s memory. If you lose this token, you get an “Access Denied” error and the user has to reinstall the app.</li></ol><h3>The Frontend Integration</h3><p>Since I didn’t use a full-stack framework like Next.js or Laravel (where packages like laravel-shopify do the heavy lifting), I built this purely on <strong>Symfony + Twig</strong>.</p><p>The integration is straightforward: grab the Shopify App Bridge CDN script and inject it into your &lt;head&gt; tag.</p><pre>&lt;head&gt; <br>    &lt;meta name=&quot;shopify-api-key&quot; content=&quot;{{ shopify_api_key }}&quot; /&gt; <br>    &lt;script src=&quot;https://cdn.shopify.com/shopifycloud/app-bridge.js&quot;&gt;&lt;/script&gt; <br>&lt;/head&gt;</pre><p><strong>Crucial detail:</strong> Ensure your meta tag correctly outputs your Client ID. If it’s missing or wrong, App Bridge will refuse to initialize.</p><p>For the backend heavy lifting (HMAC verification and authorization), the official shopify/shopify-api-php package will save you a lot of headaches.</p><p><em>Building for Shopify can be painful, but with the right architecture, it’s manageable. If this saved you some time, don’t forget to clap and subscribe.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8db0455698ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Interview Question Generator.]]></title>
            <link>https://medium.com/@fallen.snitch/building-an-ai-powered-interview-question-generator-e93caf90e855?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e93caf90e855</guid>
            <category><![CDATA[full-stack-application]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php-api]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 16:02:19 GMT</pubDate>
            <atom:updated>2026-02-09T16:02:19.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI-Powered Interview Question Generator. How to setup Symfony 7 API + Vue 3 Frontend? Part 1</h3><p>In this series, we build a small full-stack application where:</p><blockquote><em>A user selects </em><strong><em>role</em></strong><em>, </em><strong><em>position</em></strong><em>, and </em><strong><em>seniority level</em></strong><em>,<br> we send this data to an AI with a prepared prompt,<br> and the AI returns a </em><strong><em>list of interview questions</em></strong><em>.</em></blockquote><p>This is <strong>Part 1- </strong>setting up the foundation: Symfony API and Vue frontend connected together.</p><p>⚠️ This guide uses <strong>Symfony 7</strong>. Symfony 8 has some differences in defaults which I’ll mention later.</p><p>🎥 There is also a video version for those who prefer watching -<a href="https://youtu.be/-fyOqwKMpbE">link is here.</a></p><h3>What we are building</h3><p>Final flow of the app:</p><ol><li>User fills the form (role, position, level)</li><li>Vue sends request to Symfony API</li><li>Symfony sends a prompt to AI</li><li>AI returns structured interview questions</li><li>We display them in the frontend</li></ol><p>But before the interesting part — we need a clean full-stack base.</p><h4>1. Install Symfony CLI</h4><p>Download from:</p><pre>https://symfony.com/download</pre><p>Check installation:</p><pre>symfony -v</pre><h4>2. Create Symfony project</h4><pre>mkdir developer-interview<br>cd developer-interview<br>symfony new api --webapp<br>symfony serve -d</pre><p>Backend is running.</p><h4>3. Create a test API endpoint</h4><p>We need a simple JSON response to verify frontend ↔ backend connection.</p><pre>php bin/console make:controller Api/TestController</pre><p>Replace controller with:</p><pre>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br>use Symfony\Component\Routing\Annotation\Route;<br><br>class TestController extends AbstractController<br>{<br>    #[Route(&#39;/api/ping&#39;, name: &#39;api_ping&#39;, methods: [&#39;GET&#39;])]<br>    public function ping(): JsonResponse<br>    {<br>        return $this-&gt;json([&#39;message&#39; =&gt; &#39;pong&#39;]);<br>    }<br>}</pre><p>Check in browser:</p><pre>http://127.0.0.1:8000/api/ping</pre><h4>4. Create Vue 3 frontend</h4><p>From root:</p><pre>npm create vue@latest frontend</pre><p>Select Router and Prettier.</p><pre>cd frontend<br>npm install<br>npm run dev</pre><p>Runs on:</p><pre>http://localhost:5173</pre><h4>5. Connect Vue to Symfony</h4><p>In App.vue:</p><pre>import { ref, onMounted } from &#39;vue&#39;<br><br>const apiResponse = ref(null);<br><br>onMounted(async () =&gt; {<br>  const res = await fetch(&#39;http://127.0.0.1:8000/api/ping&#39;)<br>  apiResponse.value = await res.json()<br>})</pre><p>Template:</p><pre>&lt;template&gt;<br>  &lt;h1&gt;Backend connection test&lt;/h1&gt;<br>  &lt;p&gt;Response: {{ apiResponse }}&lt;/p&gt;<br>&lt;/template&gt;</pre><p>You will see a <strong>CORS error</strong>.</p><h4>6. Fix CORS</h4><pre>composer require nelmio/cors-bundle</pre><p>config/packages/nelmio_cors.yaml:</p><pre>nelmio_cors:<br>    paths:<br>        &#39;^/&#39;:<br>            allow_origin: [&#39;http://localhost:5173&#39;]<br>            allow_methods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;DELETE&#39;, &#39;OPTIONS&#39;]<br>            allow_headers: [&#39;Content-Type&#39;, &#39;Authorization&#39;]</pre><p>Restart server:</p><pre>symfony serve:stop<br>symfony serve -d</pre><h4>7. Add Tailwind (optional)</h4><pre>npm install tailwindcss @tailwindcss/vite</pre><p>In CSS:</p><pre>@import &quot;tailwindcss&quot;;</pre><h3>What we have now</h3><p>Working base for:</p><ul><li>Vue form Symfony</li><li>API endpoint</li><li>Future AI integration</li><li>Real full-stack data flow</li></ul><p>This is the foundation for our AI interview question generator. In a next part we will connect free NEON DB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e93caf90e855" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up Xdebug with Docker and PHPStorm?]]></title>
            <link>https://medium.com/@fallen.snitch/how-to-set-up-xdebug-with-docker-and-phpstorm-d3365e426ff0?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3365e426ff0</guid>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[xdebug]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 14:57:09 GMT</pubDate>
            <atom:updated>2025-08-30T14:57:09.217Z</atom:updated>
            <content:encoded><![CDATA[<p>Hola amigos! It’s very important not only to be a great developer when you create something new, but also a good bug-fixer. <a href="https://medium.com/@fallen.snitch/xdebug-3-setup-guide-on-windows-with-phpstorm-step-by-step-no-docker-needed-5633dfe1f76e">In the previous article</a>, you can check out how to set up Xdebug on your machine. After you’ve done this, you can continue here 😉</p><p>Also, I’ll show how to set it up from scratch and give examples of where you can put the config if you already have one. The setup for Laravel and Symfony in most cases will be absolutely the same.</p><h3>Tools:</h3><p>PHP v.8.3<br> Xdebug v.3.3.1<br> PhpStorm 2025.1.1 (but it will also work with the previous 2–3 versions)</p><p>If you already have a Dockerfile — open it, find the block where all PHP dependencies and extensions are installed, and paste this code:</p><pre>RUN pecl install xdebug-3.3.1 &amp;&amp; docker-php-ext-enable xdebug<br><br>RUN echo &quot;zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini \<br>    &amp;&amp; echo &quot;xdebug.mode=develop,debug&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini \<br>    &amp;&amp; echo &quot;xdebug.client_host=host.docker.internal&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini \<br>    &amp;&amp; echo &quot;xdebug.start_with_request=yes&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini \<br>    &amp;&amp; echo &quot;xdebug.idekey=PHPSTORM&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini \<br>    &amp;&amp; echo &quot;xdebug.log=/var/log/xdebug.log&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini \<br>    &amp;&amp; echo &quot;xdebug.client_port=9003&quot; &gt;&gt; /usr/local/etc/php/conf.d/xdebug.ini<br>&quot;</pre><p>Examples from one of my projects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blq3gj8Z6CTW6C6CgSd6lg.png" /></figure><p>Or you can always create your own dev.Dockerfile. In the folder docker/php/ →</p><h4>dev.Dockerfile:</h4><pre>FROM php:8.3-fpm<br><br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    libpq-dev \<br>    git \<br>    unzip \<br>    &amp;&amp; docker-php-ext-install pdo pdo_pgsql<br><br>RUN pecl install xdebug-3.3.1 \<br>    &amp;&amp; docker-php-ext-enable xdebug<br><br>COPY ./docker/php/xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini<br><br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>WORKDIR /var/www/aerobay<br><br>COPY . .<br><br>RUN php artisan l5-swagger:generate || true</pre><p>I use PostgreSQL and Laravel, but for Symfony with MySQL or any other DB it will be similar — you just need to change &quot;pdo_pgsql&quot; to &quot;pdo_mysql&quot; or whatever your DB is.</p><p>I added the Swagger documentation generation so it’s not done manually. Keep in mind: Swagger docs will be generated only once when you build the container. So if you make changes later, go inside your app container and run:</p><pre>php artisan l5-swagger:generate</pre><p>As you can notice, this time I put the Xdebug setup in a separate file, in the same folder as the config:</p><pre>zend_extension=xdebug.so<br><br>xdebug.mode=develop,debug<br>xdebug.start_with_request=yes<br>xdebug.client_host=host.docker.internal<br>xdebug.client_port=9003<br>xdebug.idekey=PHPDEBUG<br><br>xdebug.log=/tmp/xdebug.log</pre><blockquote>I specified the debugger version because right now it’s one of the stable and working ones with Docker. If you don’t set the version, it won’t work.<br> Also, you can configure Xdebug in a separate file or just leave it inline.</blockquote><p>Inside xdebug.idekey, you can write any word or phrase you wish — just remember it later 😉</p><h4>docker-compose.yaml:</h4><pre>services:<br>    app:<br>        build:<br>            context: .<br>            dockerfile: docker/php/dev.Dockerfile<br>        volumes:<br>            - ./:/var/www/aerobay<br>        depends_on:<br>            - db<br>        extra_hosts:<br>            - &quot;host.docker.internal:host-gateway&quot;<br><br>    db:<br>        image: postgres:16<br>        restart: unless-stopped<br>        environment:<br>            POSTGRES_DB: laravel<br>            POSTGRES_USER: laravel<br>            POSTGRES_PASSWORD: secret<br>        ports:<br>            - &quot;5432:5432&quot;<br>        volumes:<br>            - db_data:/var/lib/postgresql/data<br><br>    nginx:<br>        image: nginx:alpine<br>        ports:<br>            - &quot;8080:80&quot;<br>        volumes:<br>            - ./:/var/www/aerobay<br>            - ./docker/nginx/default.dev.conf:/etc/nginx/conf.d/default.conf<br>        depends_on:<br>            - app<br><br>volumes:<br>    db_data:</pre><blockquote>Use the same volume name ./:/var/www/aerobay that you wrote in your Dockerfile WORKDIR.</blockquote><p>For DB connection I recommend using a dump of your DB. In environment you can set up fake DB name, password, and user. But if you want to use your real prod DB (which I don’t recommend), refer to your .env variables.</p><p>Don’t forget that .env variables have priority. So if you already have DB setup but want to work with a dump, refer to it like this:</p><pre>services:<br>  db:<br>    image: postgres:16<br>    restart: unless-stopped<br>    env_file:<br>      - .env.dev <br>    environment:<br>      POSTGRES_DB: ${DB_DATABASE}<br>      POSTGRES_USER: ${DB_USERNAME}<br>      POSTGRES_PASSWORD: ${DB_PASSWORD}<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - db_data:/var/lib/postgresql/data</pre><p>I added a new .env.dev file and put my variables there.</p><p>And last but not least — a separate file for Nginx.<br> If you watched my video <em>“</em><a href="https://medium.com/@fallen.snitch/free-laravel-11-deployment-on-render-with-docker-6487a9a09e57"><em>How to deploy Laravel on Render?</em></a><em>”</em>, you may already have a Nginx file. But for local dev, we create a new one. Name it:</p><h4>default.dev.conf</h4><pre>server {<br>    listen 80;<br>    server_name localhost;<br><br>    root /var/www/aerobay/public;<br>    index index.php index.html;<br><br>   location /docs {<br>       alias /var/www/aerobay/storage/api-docs/;<br>       index index.html;<br>       try_files $uri /api-docs.json;<br>   }<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    location ~ \.php$ {<br>        include fastcgi.conf;<br>        fastcgi_pass app:9000;<br>        fastcgi_index index.php;<br>        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;<br>        fastcgi_param DOCUMENT_ROOT $realpath_root;<br>    }<br><br>    location ~* \.(jpg|jpeg|gif|png|css|js|ico|webp|ttf|svg)$ {<br>        expires 5d;<br>        access_log off;<br>        log_not_found off;<br>    }<br><br>    location ~ /\. {<br>        deny all;<br>    }<br><br>    location = /favicon.ico { access_log off; log_not_found off; }<br>    location = /robots.txt  { access_log off; log_not_found off; }<br><br>    charset utf-8;<br>}</pre><blockquote>I added the /docs block for my Swagger documentation. If you’re writing Symfony with Nelmio or not building an API at all, you can just remove this block.</blockquote><p>Finally, let’s move on to the setup in <strong>PHPStorm</strong>.</p><p>In “Settings”, block “PHP Section” go to “Servers”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTu3pGAVEDPGIZqnVgaAHQ.png" /></figure><p>Create name, inside port input value should be the same as in docker-compose port for nginx <strong><em>ports: — “8080:80”, </em></strong>take first one<strong><em>. </em></strong>For absolute path — the same path we wrote in Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*I8kE0I7_vJ6MAe-F3n4MUQ.png" /><figcaption>Moving to the debug Tab</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wsk5QnTxHH29MpcpJ1K9_A.png" /><figcaption>Choose “Edit Configuration” -&gt; “Edit”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBiFI2xQ-C2ol0uKuq2ROA.png" /><figcaption>Click on “+” icon, choose “PHP Remote Debug”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOazgHY_vc7DcqEhRTuUvw.png" /><figcaption>In “Server” using name which I created in “Serves” and !IDE key! Remember? We put it in php.ini</figcaption></figure><p>Finally, let’s build our Docker image and start containers:</p><pre>docker-compose build<br>docker-compose up -d</pre><p>Set break points, enable debugger, go to website, trigger debugger and enjoy debugging process 🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3365e426ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free Laravel 11 Deployment on Render with Docker]]></title>
            <link>https://medium.com/@fallen.snitch/free-laravel-11-deployment-on-render-with-docker-6487a9a09e57?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6487a9a09e57</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[how-to-deploy-app]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[render]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Sat, 10 May 2025 11:56:28 GMT</pubDate>
            <atom:updated>2025-05-30T12:12:53.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDewZwJelbEV8_8S7jUkUQ.jpeg" /></figure><p>Deploying your Laravel 11 backend for free? Yes, it’s possible — and in this guide, I’ll walk you through every step of deploying a Laravel project on Render using Docker. Whether you’re building a side project or just want to test something quickly, this setup is clean, modern, and cost-effective.</p><blockquote>You can watch video instruction here: <a href="https://youtu.be/XFqwk0z3Tqw?si=xDwcXNiEsD2J-JKm">https://youtu.be/XFqwk0z3Tqw?si=xDwcXNiEsD2J-JKm</a></blockquote><h3>Tools You’ll Need</h3><p>Before we dive in, make sure you have the following:</p><ul><li><strong>Docker</strong> installed on your machine.</li><li><strong>An IDE</strong> — I recommend PHPStorm, but use what you like.</li></ul><p>If you haven’t installed Docker yet, visit the official Docker website and follow the instructions for your OS.</p><h3>Assuming you already have a Laravel project (mine includes a basic CRUD controller and Swagger docs), let’s prepare it for Docker deployment.</h3><h4><strong>Create a </strong><strong>Dockerfile in your project root:</strong></h4><pre>FROM richarvey/nginx-php-fpm:latest<br><br>COPY . .<br><br># Image config<br>ENV SKIP_COMPOSER 1<br>ENV WEBROOT /var/www/html/public<br>ENV PHP_ERRORS_STDERR 1<br>ENV RUN_SCRIPTS 1<br>ENV REAL_IP_HEADER 1<br><br># Laravel config<br>ENV APP_ENV production<br>ENV APP_DEBUG false<br>ENV LOG_CHANNEL stderr<br><br><br># Allow composer to run as root<br>ENV COMPOSER_ALLOW_SUPERUSER 1<br><br>CMD [&quot;/start.sh&quot;]</pre><h4>Create a .dockerignore file:</h4><pre>vendor/<br>node_modules/</pre><h4>Create a start.sh script:</h4><pre>#!/usr/bin/env bash<br>echo &quot;Running composer&quot;<br><br>composer install --no-dev --working-dir=/var/www/html<br><br>echo &quot;Caching config...&quot;<br>php artisan config:cache<br><br>echo &quot;Caching routes...&quot;<br>php artisan route:cache<br><br>echo &quot;Publishing cloudinary provider...&quot;<br>php artisan vendor:publish --provider=&quot;CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider&quot; --tag=&quot;cloudinary-laravel-config&quot;<br><br>echo &quot;Running migrations...&quot;<br>php artisan migrate --force<br></pre><h4>Add a Render-compatible deploy script. Create a folder called scripts and inside it a file: 00-laravel-deploy.sh.</h4><p>Render will automatically execute this script during deployment. Include Laravel prep steps here too.</p><pre>#!/usr/bin/env bash<br>echo &quot;Running composer&quot;<br><br>composer install --no-dev --working-dir=/var/www/html<br><br>echo &quot;Caching config...&quot;<br>php artisan config:cache<br><br>echo &quot;Caching routes...&quot;<br>php artisan route:cache<br><br><br>echo &quot;Publishing cloudinary provider...&quot;<br>php artisan vendor:publish --provider=&quot;CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider&quot; --tag=&quot;cloudinary-laravel-config&quot;</pre><h4>Nginx Config.</h4><p>Create conf/nginx/nginx-site.conf and configure it to serve from the Laravel public/ directory.</p><pre>server {<br>  # Render provisions and terminates SSL<br>  listen 80;<br><br>  # Make site accessible from http://localhost/<br>  server_name _;<br><br>  root /var/www/html/public;<br>  index index.html index.htm index.php;<br><br>  # Disable sendfile as per https://docs.vagrantup.com/v2/synced-folders/virtualbox.html<br>  sendfile off;<br><br>  # Add stdout logging<br>  error_log /dev/stdout info;<br>  access_log /dev/stdout;<br><br>  # block access to sensitive information about git<br>  location /.git {<br>    deny all;<br>    return 403;<br>  }<br><br>  add_header X-Frame-Options &quot;SAMEORIGIN&quot;;<br>  add_header X-XSS-Protection &quot;1; mode=block&quot;;<br>  add_header X-Content-Type-Options &quot;nosniff&quot;;<br><br>  charset utf-8;<br><br>  location / {<br>      try_files $uri $uri/ /index.php?$query_string;<br>  }<br><br>  location = /favicon.ico { access_log off; log_not_found off; }<br>  location = /robots.txt  { access_log off; log_not_found off; }<br><br>  error_page 404 /index.php;<br>   location ~ (^/docs/asset/.*) {<br>     try_files $uri $uri/ /index.php$is_args$args;<br>   }<br>  location ~* \.(jpg|jpeg|gif|png|css|js|ico|webp|tiff|ttf|svg)$ {<br>    expires 5d;<br>  }<br><br>  location ~ \.php$ {<br>    fastcgi_split_path_info ^(.+\.php)(/.+)$;<br>    fastcgi_pass unix:/var/run/php-fpm.sock;<br>    fastcgi_index index.php;<br>    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>    fastcgi_param SCRIPT_NAME $fastcgi_script_name;<br>    include fastcgi_params;<br>  }<br><br>  # deny access to . files<br>  location ~ /\. {<br>    log_not_found off;<br>    deny all;<br>  }<br><br>  location ~ /\.(?!well-known).* {<br>    deny all;<br>  }<br>}</pre><p>Inside <strong>App\Http\Kernel.php</strong>: Ensure api middleware includes cors and SubstituteBindings :</p><pre>  protected $middlewareGroups = [<br>        &#39;web&#39; =&gt; [<br>            \App\Http\Middleware\VerifyCsrfToken::class,<br>        ],<br><br>        &#39;api&#39; =&gt; [<br>            &#39;cors&#39;,<br>            \Illuminate\Routing\Middleware\SubstituteBindings::class,<br>        ],<br>    ];</pre><h4>Build and Push Docker Image.</h4><p>Go to Docker Hub, sign in, and create a new <strong>public</strong> repository.</p><blockquote>🔒 Render’s free plan <strong>does not</strong> support private images!</blockquote><p>Build your Docker image:</p><p><strong>For Windows/Linux:</strong></p><pre>docker build -t yourusername/your-repo-name .</pre><p><strong>For Mac (Apple Silicon):</strong></p><pre>docker buildx build --platform linux/amd64 -t yourusername/your-repo-name .</pre><p><strong>Push to Docker Hub:</strong></p><pre>docker push yourusername/your-repo-name</pre><p>Check Docker Hub to ensure the image was uploaded successfully.</p><h3>🌐 Deploy on Render</h3><ol><li>Head to <a href="https://render.com/">Render.com</a> and log in.</li><li>Click <strong>New Web Service</strong> → <strong>Use an existing Docker image</strong>.</li><li>Enter your image URL: yourusername/your-repo-name:latest</li><li>Choose the <strong>Free plan</strong>.</li><li>Set environment variables (e.g., DB connection details).</li><li>Click <strong>Deploy Web Service</strong></li></ol><p>That’s it! Your Laravel app is now deploying. This setup is ideal for side projects, prototypes, or even small production apps. Let me know in the comments if it worked for you, or if you ran into any issues.</p><p>If you found this guide helpful, don’t forget to <strong>clap</strong>, <strong>follow</strong>, and <strong>share</strong>. Happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6487a9a09e57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xdebug 3 Setup Guide on Windows with PHPStorm: Step-by-Step (No Docker Needed)]]></title>
            <link>https://medium.com/@fallen.snitch/xdebug-3-setup-guide-on-windows-with-phpstorm-step-by-step-no-docker-needed-5633dfe1f76e?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5633dfe1f76e</guid>
            <category><![CDATA[php-debug]]></category>
            <category><![CDATA[xdebug]]></category>
            <category><![CDATA[debugging-tools]]></category>
            <category><![CDATA[laravel-debugbar]]></category>
            <category><![CDATA[setup]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 12:54:49 GMT</pubDate>
            <atom:updated>2024-12-20T12:59:29.720Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to step-by-step guide, if you need to guide, how to set up xdebug using Docker or to set up on Mac, as well — just let me know in the comments. Don’t forget to click clap and subscribe 🙃</p><h4><strong>Step 1: Download and Install Xdebug</strong></h4><p>Let’s start from downloading x-debug on your laptop. Navigate to <a href="https://xdebug.org/wizard"><strong>https://xdebug.org/wizard</strong></a><em> </em>and follow instructions above the form on screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pi9s0uEe22mvLPZ76HiBBA.png" /></figure><p>After submitting the form, you will see something like this. I’ve already installed it, that’s why I have line with version.</p><p>Ensure your PHPStorm project is running on the same PHP version as the Xdebug configuration. If you accidentally configure PHPStorm to use a different version of PHP (e.g., 7.4), Xdebug might not work because each PHP version has its own php_xdebug.dll file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*hlqL84-vZnmgHRyeqKItjA.jpeg" /></figure><p>Following instructions, create folder <strong>“ext”</strong> on disk C, or whatever is suitable for you, rename file to <strong>php_xdebug.dll</strong> and save it.</p><h4><strong>Step 2: Configure php.ini</strong></h4><p>Next step, add configuration to php.ini file. Find block after “extensions” and paste this code:</p><pre>zend_extension = xdebug<br><br>[xdebug]<br><br>xdebug.mode = debug<br>xdebug.start_with_request=yes<br>xdebug.client_host=127.0.0.1<br>xdebug.client_port=9003<br>xdebug.log=&quot;C:\php\logs\xdebug.log&quot;<br>xdebug.log_level=7<br>xdebug.remote_enable = 1<br>xdebug.remote_autostart = 1</pre><p>Don’t forget to save the changes. Below is a screenshot of my php.ini file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*e7rbh9mo-0A-GQgxPVa7pQ.jpeg" /></figure><h4><strong>Step 3: Install Xdebug Helper in Chrome</strong></h4><p>Few more steps before final, turn to Chrome browser and put up Xdebug helper extension: <a href="https://chromewebstore.google.com/detail/xdebug-helper/eadndfjplgieldjbigjakmdgkmoaaaoc"><strong>https://chromewebstore.google.com/detail/xdebug-helper/eadndfjplgieldjbigjakmdgkmoaaaoc</strong></a></p><p>In extension bar will appear this icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*PERzW7oHt7Qiim2Zsc3ODw.jpeg" /></figure><p>Turn on debug mode on tab, where your app is running. Right mouse click on icon, go to “Settings”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Xsh35loAt0wseveNCGybbw.jpeg" /></figure><p>Select IDE key as PHPStorm and save it.</p><h4><strong>Step 4: Configure PHPStorm</strong></h4><p>Pre final step, in PHPStorm IDE pick “Settings” -&gt; “PHP”-&gt; “Debug”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvIQsp27LUvhP0yEfZOIag.png" /></figure><p>Important notice — port which we wrote above in php.ini and port in PHPStorm should be the same. Otherwise, it won’t work.</p><h4>Step 5: Start Debugging</h4><p>Finally, turn on debug in PHPStorm, it should be green like on screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*vIdCQrmkR_NVIGsIi6ieHw.png" /></figure><p>Set break points, go to your website, trigger debugger and enjoy debugging process 🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uw-mhpgyRhRMyrn4f3yHgw.jpeg" /></figure><p>Please, if you find this guide useful, make clap and subscribe. Happy coding and take care 🩶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5633dfe1f76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create full-stack page in Symfony? Entity, migrations, form builder and twig template.]]></title>
            <link>https://medium.com/@fallen.snitch/how-to-create-full-stack-page-in-symfony-entity-migrations-form-builder-and-twig-template-96c6919da33c?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c6919da33c</guid>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[symfony-framework]]></category>
            <category><![CDATA[symfony-entity]]></category>
            <category><![CDATA[symfony-6]]></category>
            <category><![CDATA[twig]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 06:16:57 GMT</pubDate>
            <atom:updated>2024-12-05T14:53:08.426Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I want to share my experience, how to create a full-stack page with Symfony. You could use this template for other pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*zEqlHzSKTIqjSYzYq6zuqg.png" /></figure><p><strong>Used versions:</strong><br>symfony - 6.4,<br>doctrine/orm — 2.20</p><p>My objective was to create a page in admin panel, where a user (or next admin) can add job advertisements (next vacancies), an opportunity to show or hide. So when, admin click option “Visible” it should be immediately publish on web-site section with vacancies.</p><p>So, let’s start with creating an entity, execute the next command:</p><pre>php bin/console make:entity</pre><figure><img alt="Give name your entity in my case Vacancy" src="https://cdn-images-1.medium.com/max/536/1*SaQ_Aq9ieSrRaMflcs_gsw.jpeg" /><figcaption>Give name your entity in my case Vacancy</figcaption></figure><p>Continue: name the fields, set type and length. In case, when type is string or nullable, you can set up NULL value as default.<br>As for me, it’s suitable to define all other fields manually, here is all up to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*E0VijUDSsQldSbRNUlT98A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*j32gmj4xX7qwWczd16muwg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*p8YwrZymkc-3CVMYBFaPbg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*G0jJ2vmm6e7SwwuGsWKqZw.jpeg" /></figure><p>As I mention above, you are able to leave some fields with NULL value in DB. To achieve this, just mark it as nullable, as it’s shown below:</p><pre> #[ORM\Column(length: 255, nullable: true)]</pre><p>To let DB an information that DB structure or table design was changed, it’s necessary to execute next command and make a migration:</p><pre>php bin/console make:migration</pre><p>The created migration is placed in the Migrations folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*NnYTX7qjPF4dEBUSWMtT_A.png" /></figure><p>Use class name “Version2024…..” (what is in your migration) and enter:</p><pre>php bin/console doctrine:migrations:migrate &#39;DoctrineMigrations\Version20241003080048&#39;</pre><p>Execute next command to solve the problems when you have run into some anomalies (for instance, my first migration just skipped some fields):</p><pre>php bin/console doctrine:cache:clear-metadata</pre><p>Afterwards, reproduce steps before: make migration and migrate new Version.</p><p>Move on to the next, important part — creating controller.</p><p>To implement your first base method, look at my code for vacancies page. As you can see the name of this method is “index”, so you have to create the twig-template with the same name “index.html.twig”. We will use this template to provide a user an information about the vacancies.</p><pre>class VacancyController extends AbstractController<br>{<br><br>    #[Route(path: &#39;/admin/vacancies/&#39;, name: &#39;admin_vacancies&#39;)]<br>    public function index(): Response<br>    {<br>        return $this-&gt;render(&#39;admin/vacancy/index.html.twig&#39;);<br>    }<br>}</pre><p>For now, we didn’t path any information in our twig, so let&#39;s add some HTML and CSS, just check, that’s everything is working fine.</p><p>In my project, I have base admin.template.twig, where I use repeated parts as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQrtc_aZekD-ytZsbLO2Tw.png" /></figure><p>Or sidebar menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Jp3OdccLEbMJthJJ4nUaA.png" /></figure><p>Here is my marking, for start:</p><pre>{% extends &#39;admin.html.twig&#39; %}<br>{% block body %}<br>    &lt;div class=&quot;team__headline&quot;&gt;<br>        &lt;h1&gt;Vacancy List&lt;/h1&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;toolbar&quot;&gt;<br>        &lt;button id=&quot;button-add&quot; class=&quot;btn btn-primary&quot;&gt;Add&lt;/button&gt;<br>    &lt;/div&gt;<br>{% endblock %}</pre><p>Go to your browser and check it’s working:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijWR3w0XgbfsZFMmzLy_1Q.jpeg" /></figure><p>Inject EntityManagerInterface to get all vacancies from DB in advance. At this moment, we don’t have any data, but we’ll add this further.</p><pre>public function __construct(<br>        private readonly EntityManagerInterface $em,<br>    )<br>    {<br>    }</pre><pre>  #[Route(path: &#39;/admin/vacancies/&#39;, name: &#39;admin_vacancies&#39;)]<br>    public function index(): Response<br>    {<br>        $vacancies = $this-&gt;em-&gt;getRepository(Vacancy::class)-&gt;findAll();<br>        return $this-&gt;render(&#39;admin/vacancy/index.html.twig&#39;, [<br>            &#39;vacancies&#39; =&gt; $vacancies,<br>        ]);<br>    }</pre><p>Diving deeper, become more interesting, because to have possibility add vacancies, firstly — realize new method and create form, using built in Symfony tool.</p><pre>  #[Route(path: &#39;/admin/vacancies/add/&#39;, name: &#39;admin_vacancies_add&#39;)]<br>    public function addAction(Request $request): Response<br>    {<br>        $vacancy = new Vacancy();<br>        $form = $this-&gt;createForm(VacancyType::class, $vacancy);<br>    }</pre><p>I gave name to my future form “VacancyType” in “Form\AdminPages” folder</p><pre>namespace App\Form\AdminPages;<br><br>use Symfony\Component\Form\AbstractType;<br><br>class VacancyType extends AbstractType<br>{<br>    <br>}</pre><p>Built fields, which you have declared in Entity. Determine type of fields. In description, I used <strong>CKEditorType. </strong>It’s provide more options to edit, mark and change style of text.</p><pre>class VacancyType extends AbstractType<br>{<br><br>    public function buildForm(FormBuilderInterface $builder, array $options): void<br>    {<br>        $builder<br>            -&gt;add(&#39;title&#39;, TextType::class, [<br>                &#39;attr&#39; =&gt; [&#39;class&#39; =&gt; &#39;vacancy-form-control&#39;],<br>                &#39;required&#39; =&gt; false,<br>            ])<br>            -&gt;add(&#39;subtitle&#39;, TextType::class, [<br>                &#39;attr&#39; =&gt; [&#39;class&#39; =&gt; &#39;vacancy-form-control&#39;],<br>                &#39;required&#39; =&gt; false,<br>            ])<br>            -&gt;add(&#39;description&#39;, CKEditorType::class, [&#39;label&#39; =&gt; false])<br>            -&gt;add(&#39;visible&#39;, CheckboxType::class, [<br>                &#39;required&#39; =&gt; false,<br>                &#39;attr&#39; =&gt; [&#39;class&#39; =&gt; &#39;vacancy-form-control-btn&#39;]<br>            ])<br>            -&gt;add(&#39;link&#39;, TextType::class, [<br>                &#39;attr&#39; =&gt; [&#39;class&#39; =&gt; &#39;vacancy-form-control&#39;],<br>                &#39;required&#39; =&gt; false,<br>            ]);<br>    }<br><br>    /**<br>     * @param OptionsResolver $resolver<br>     */<br>    public function configureOptions(OptionsResolver $resolver)<br>    {<br>        $resolver-&gt;setDefaults([<br>            &#39;data_class&#39; =&gt; Vacancy::class,<br>        ]);<br>    }<br>}</pre><p>Read more about CKEditorType <a href="https://symfony.com/bundles/FOSCKEditorBundle/current/index.html">here</a>, finally it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*AAN-6aqp0SEgCcrEwHNYlg.png" /><figcaption>CKEditor</figcaption></figure><p>When it’s done — get the form, check it’s valid (if necessary) and save the record into DB. Pass form and vacancy-data in template. For the “Add”-section, I’ve created a separate template.</p><pre>  $vacancy = new Vacancy();<br>  $form = $this-&gt;createForm(VacancyType::class, $vacancy);<br>  $form-&gt;handleRequest($request);<br><br> if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {<br>     $this-&gt;em-&gt;persist($vacancy);<br>     $this-&gt;em-&gt;flush();<br>   }<br><br> return $this-&gt;render(&#39;admin/vacancy/add.html.twig&#39;, [<br>        &#39;form&#39; =&gt; $form-&gt;createView(),<br>        &#39;vacancy&#39; =&gt; $vacancy,<br> ]);</pre><p>Here’s my example:</p><pre>{% extends &#39;admin.html.twig&#39; %}<br>{% block body %}<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;header__vacancy&quot;&gt;<br>            &lt;h3&gt;Add new vacancy&lt;/h3&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    {{ form_start(form) }}<br>    &lt;div class=&quot;container &quot;&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;col-md-8&quot;&gt;<br>            &lt;div class=&quot;row about-teammate&quot;&gt;<br>                &lt;div class=&quot;col-md-12 mt-4&quot;&gt;<br>                    {{ form_row(form.title) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4&quot;&gt;<br>                    {{ form_row(form.subtitle) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4&quot;&gt;<br>                    {{ form_row(form.description) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4&quot;&gt;<br>                    {{ form_row(form.link) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4 team-form-control-checkbox&quot;&gt;<br>                    &lt;label for=&quot;{{ vacancy.visible }}&quot; class=&quot;custom-checkbox-label&quot;&gt;<br>                        {{ form_widget(form.visible, { &#39;attr&#39;: {&#39;class&#39;: &#39;vacancy-form-control-btn&#39;} }) }}<br>                    &lt;/label&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4&quot;&gt;<br>                    &lt;button class=&quot;btn btn-success btn-reset&quot;&gt;{{ button_label|default(&#39;Save&#39;) }}&lt;/button&gt;<br>                    &lt;button type=&quot;button&quot; class=&quot;btn btn-outline-secondary&quot;<br>                    &gt;{{ button_label|default(&#39;Cancel&#39;) }}&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    {{ form_end(form) }}<br>{% endblock %}</pre><p>Add more styles in your CSS file, connect using “link” :</p><pre>{% block stylesheets %}<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ asset(&#39;css/custom.css&#39;) }}&quot;&gt;<br>{% endblock %}</pre><p>Or second option, describe it in the same template. After <strong>{% endblock %} </strong>paste<strong> :</strong></p><pre>{% block stylesheets %}<br>    &lt;style&gt;<br>        //your styles<br>        body {<br>            background-color: #f0f0f0;<br>        }<br>    &lt;/style&gt;<br>{% endblock %}</pre><p>Return to index page to see is it really working. I have attached some markup:</p><pre>{% extends &#39;admin.html.twig&#39; %}<br>{% block body %}<br>    &lt;div class=&quot;vacancy__headline&quot;&gt;<br>        &lt;h1&gt;Vacancy List&lt;/h1&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;toolbar mb-3&quot;&gt;<br>        &lt;button id=&quot;button-add&quot; class=&quot;btn btn-primary&quot;&gt;Add&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;table id=&quot;table&quot; class=&quot;table__vacancy table table-striped table-bordered&quot;&gt;<br>        &lt;thead&gt;<br>        &lt;tr&gt;<br>            &lt;th data-field=&quot;title&quot;&gt;Title&lt;/th&gt;<br>            &lt;th data-field=&quot;subtitle&quot;&gt;Subtitle&lt;/th&gt;<br>            &lt;th data-field=&quot;description&quot;&gt;Description&lt;/th&gt;<br>            &lt;th data-field=&quot;visible&quot;&gt;Visible&lt;/th&gt;<br>        &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>        {% for vacancy in vacancies %}<br>            &lt;tr&gt;<br>                &lt;td&gt;{{ vacancy.title }}&lt;/td&gt;<br>                &lt;td&gt;{{ vacancy.subtitle }}&lt;/td&gt;<br>                &lt;td data-field=&quot;vacancy__description&quot;&gt;{{ vacancy.description }}&lt;/td&gt;<br>                &lt;td&gt;{{ vacancy.visible ? &#39;Yes&#39; : &#39;No&#39; }}&lt;/td&gt;<br>                &lt;td&gt;<br>                    &lt;button id=&quot;button-edit&quot; class=&quot;btn btn-primary btn-sm mr-2&quot; onclick=&quot;editItem({{ vacancy.id }})&quot;&gt;&lt;i<br>                                class=&quot;fa fa-edit&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                    &lt;button class=&quot;btn btn-danger btn-sm&quot; data-bs-target=&quot;#deleteVacancy&quot;<br>                            onclick=&quot;prepareDelete({{ vacancy.id }})&quot;&gt;&lt;i<br>                                class=&quot;fa fa-trash&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;/td&gt;<br>            &lt;/tr&gt;<br>        {% endfor %}<br>        &lt;/tbody&gt;<br>    &lt;/table&gt;<br><br>{% endblock %}</pre><p>Make the button interactive:</p><pre> {% block javascripts %}<br>          &lt;script&gt;<br>              $(function () {<br>                  $(document).ready(function () {<br>                      $(&#39;#button-add&#39;).on(&#39;click&#39;, function () {<br>                          window.location.href = &#39;/admin/vacancies/add/&#39;;<br>                      });<br>                  });<br>              })<br>          &lt;/script&gt;<br>      {% endblock %}</pre><p>The same need to do with “Edit” and “Delete” actions. For both, create separate methods, where pass the ID.</p><pre>#[Route(path: &#39;/admin/vacancy/edit/{id}/&#39;, name: &#39;admin_vacancies_edit&#39;)]<br>    public function editAction(Request $request, int $id): Response<br>    {<br>        $vacancy = $this-&gt;em-&gt;getRepository(Vacancy::class)-&gt;find($id);<br>        $form = $this-&gt;createForm(VacancyType::class, $vacancy);<br><br>        $form-&gt;handleRequest($request);<br>        if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {<br>            $this-&gt;em-&gt;flush();<br>            return $this-&gt;redirectToRoute(&#39;admin_vacancies&#39;);<br>        }<br>        return $this-&gt;render(&#39;admin/vacancy/edit.html.twig&#39;, [<br>            &#39;form&#39; =&gt; $form-&gt;createView(),<br>            &#39;vacancy&#39; =&gt; $vacancy,<br>        ]);<br>    }</pre><p>In edit.html.twig template:</p><pre>{% extends &#39;admin.html.twig&#39; %}<br>{% block body %}<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;header__vacancy&quot;&gt;<br>            &lt;h3&gt;Edit vacancy&lt;/h3&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    {{ form_start(form) }}<br>    &lt;div class=&quot;container &quot;&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;col-md-8&quot;&gt;<br>            &lt;div class=&quot;row about-vacancy&quot;&gt;<br>                &lt;div class=&quot;col-md-12&quot;&gt;<br>                    {{ form_row(form.title) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12&quot;&gt;<br>                    {{ form_row(form.subtitle) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12&quot;&gt;<br>                    {{ form_row(form.description) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12&quot;&gt;<br>                    {{ form_row(form.link) }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4 vacancy-form-control-checkbox&quot;&gt;<br>                    &lt;label for=&quot;{{ vacancy.visible }}&quot; class=&quot;custom-checkbox-label&quot;&gt;<br>                        {{ form_widget(form.visible, { &#39;attr&#39;: {&#39;class&#39;: &#39;vacancy-form-control-btn&#39;} }) }}<br>                    &lt;/label&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-md-12 mt-4&quot;&gt;<br>                    &lt;button class=&quot;btn btn-success&quot;&gt;{{ button_label|default(&#39;Save&#39;) }}&lt;/button&gt;<br>                    &lt;button type=&quot;button&quot; class=&quot;btn btn-outline-secondary&quot; onclick=&quot;returnToMain()&quot;&gt;Cancel&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    {{ form_end(form) }}<br>{% endblock %}</pre><p>For now, I added and hardcode the button, which return to the main page. However, in real projects it’s a bad-practice.</p><pre>   &lt;button type=&quot;button&quot; class=&quot;btn btn-outline-secondary&quot;<br>      onclick=&quot;window.location.href = `/admin/vacancies/`&quot;&gt;Cancel<br>   &lt;/button&gt;</pre><p>Make the “Edit” button interactive</p><pre>    function editItem(id) {<br>      window.location.href = `/admin/vacancy/edit/${id}/`;<br>    }</pre><p>As I mentioned before, implement separate method for “Delete” action:</p><pre> #[Route(path: &#39;/admin/vacancy/delete/{id}/&#39;, name: &#39;admin_vacancies_delete&#39;)]<br>    public function removeAction($id)<br>    {<br>        $vacancy = $this-&gt;em-&gt;getRepository(Vacancy::class)-&gt;find($id);<br>        $this-&gt;em-&gt;remove($vacancy);<br>        $this-&gt;em-&gt;flush();<br>        $this-&gt;addFlash(&#39;success&#39;, &#39;Vacancy succesfully deleted!&#39;);<br>        return $this-&gt;redirectToRoute(&#39;admin_vacancies&#39;);<br><br>    }</pre><p>Before “final” delete from DB, we should be sure, that user didn’t miss click. That’s why, implement modal-window to confirm or cancel action. This part of code, I added at the index.html.twig template.</p><pre> &lt;div class=&quot;modal-dialog modal-dialog-centered&quot; data-bs-toggle=&quot;modal&quot;&gt;<br>        &lt;div class=&quot;modal fade&quot; id=&quot;deleteVacancy&quot; tabindex=&quot;-1&quot; aria-labelledby=&quot;deleteVacancy&quot;<br>             aria-hidden=&quot;false&quot;&gt;<br>            &lt;div class=&quot;modal-dialog&quot;&gt;<br>                &lt;div class=&quot;modal-content&quot;&gt;<br>                    &lt;div class=&quot;modal-body&quot;&gt;<br>                        &lt;h4&gt;Are you sure you want to delete this record?&lt;/h4&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;modal-footer&quot;&gt;<br>                        &lt;button type=&quot;button&quot; class=&quot;btn btn-secondary&quot; data-bs-dismiss=&quot;modal&quot; id=&quot;cancelDelete&quot;&gt;<br>                            Close<br>                        &lt;/button&gt;<br>                        &lt;button type=&quot;button&quot; class=&quot;btn btn-danger&quot; id=&quot;confirmDelete&quot;&gt;Confirm&lt;/button&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;</pre><p>To make it interactive:</p><pre>            let itemIdToDelete;<br><br>              function prepareDelete(id) {<br>                  itemIdToDelete = id;<br>                  $(&#39;#deleteVacancy&#39;).modal(&#39;show&#39;);<br>              }<br><br>              $(document).ready(function () {<br>                  $(&#39;#cancelDelete&#39;).on(&#39;click&#39;, function () {<br>                      $(&#39;#deleteVacancy&#39;).modal(&#39;hide&#39;);<br>                  });<br>              });<br><br>              $(document).ready(function () {<br>                  $(&#39;#confirmDelete&#39;).on(&#39;click&#39;, function () {<br>                      deleteItem(itemIdToDelete);<br>                  });<br>              });<br><br><br>              function deleteItem(id) {<br>                  $.ajax({<br>                      url: `/admin/vacancy/verwijderen/${id}/`,<br>                      method: &#39;DELETE&#39;,<br>                      success: function (response) {<br>                          $(`#item-${id}`).remove();<br>                          location.reload();<br>                          $(&#39;#deleteVacancy&#39;).modal(&#39;hide&#39;);<br>                      },<br>                      error: function () {<br>                          alert(&#39;An error occurred while deleting the item.&#39;);<br>                      }<br>                  })<br>              }<br><br></pre><p>At this moment, we have all working pages, but they are all in Admin Panel. To display them, in our website for user: go to controller, where you render job advertisements and obtain data from DB.</p><pre>public function jobsPage(): Response<br>    {<br>        $vacancies = $this-&gt;em-&gt;getRepository(Vacancy::class)-&gt;findBy([&#39;visible&#39; =&gt; true]);<br>        return $this-&gt;render(&#39;jobs-page/index.html.twig&#39;, [<br>            &#39;vacancies&#39; =&gt; $vacancies,<br>        ]);<br>    }</pre><p>Now you can render in template, but with small trick:</p><pre> {% for vacancy in vacancies %}<br>        &lt;section class=&quot;jobDetails&quot;&gt;<br>            &lt;div class=&quot;jobDetails__banner jobDetails__banner--office-manager&quot;<br>                 style=&quot;background-image: url(https://medium.com/&#39;{{%20vich_uploader_asset(vacancy.image,%20&#39;file&#39;) }}&#39;);&quot;&gt;<br>                &lt;div class=&quot;jobDetails__banner__container container&quot;&gt;<br>                    &lt;h2 class=&quot;jobDetails__banner__title jobDetails__banner__title--space&quot;&gt;{{ vacancy.title }}&lt;/h2&gt;<br>                    {% if vacancy.subtitle is not empty %}<br>                        &lt;p class=&quot;jobDetails__banner__text&quot;&gt;{{ vacancy.subtitle }}&lt;/p&gt;<br>                    {% endif %}<br>                    &lt;div class=&quot;jobDetails__banner__btn&quot;&gt;<br>                        &lt;a href=&quot;{{ vacancy.link }}&quot;<br>                           target=&quot;_blank&quot; rel=&quot;nofollow&quot; class=&quot;jobDetails__banner__btn__link&quot;&gt;Solliciteren&lt;/a&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;svg class=&quot;jobDetails__iconSVG jobDetails__iconSVG--intern&quot;&gt;<br>                &lt;use xlink:href=&quot;#icon-dots&quot;&gt;&lt;/use&gt;<br>            &lt;/svg&gt;<br>            &lt;div class=&quot;jobDetails__container container&quot;&gt;<br>                &lt;div class=&quot;jobDetails__details&quot;&gt;<br>                    {{ vacancy.description | striptags(&#39;&lt;p&gt;&lt;br&gt;&lt;strong&gt;&lt;h1&gt;&lt;h2&gt;&lt;h3&gt;&lt;h4&gt;&lt;h5&gt;&lt;h6&gt;&lt;ul&gt;&lt;ol&gt;&lt;li&gt;&#39;) | raw }}<br>                &lt;/div&gt;<br>                &lt;div class=&quot;jobDetails__showMore&quot;&gt;<br>                    &lt;span class=&quot;jobDetails__showMore__btn js__showmore-job&quot;&gt;Lees meer&lt;/span&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/section&gt;<br>   {% endfor %}</pre><p>In Twig, striptags is used to remove all HTML tags from a string except those explicitly allowed. Here, it removes all tags from vacancy.description except for &lt;p&gt;, &lt;br&gt;, &lt;strong&gt;, and heading and list tags &lt;h1&gt;–&lt;h6&gt;, &lt;ul&gt;, &lt;ol&gt;, and &lt;li&gt;. This helps keep specific HTML elements for formatting while discarding others, which may be untrusted or unwanted.</p><pre>{{ vacancy.description | striptags(&#39;&lt;p&gt;&lt;br&gt;&lt;strong&gt;&lt;h1&gt;&lt;h2&gt;&lt;h3&gt;&lt;h4&gt;&lt;h5&gt;&lt;h6&gt;&lt;ul&gt;&lt;ol&gt;&lt;li&gt;&#39;) | raw }}</pre><p>The | raw filter in Twig is used to display the HTML content as-is without escaping it, ensuring that the tags allowed by striptags are rendered properly in the final output.</p><p>Thank you, for reading this article. Write, below in the comments, what else you want to read about Symfony. Hope, it was useful, please, clap, share and subscribe 🩶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c6919da33c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review on free OpenWeather API and usage. What problem I could have?]]></title>
            <link>https://medium.com/@fallen.snitch/review-on-free-openweather-api-and-usage-what-problem-i-could-have-910b394c45e4?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/910b394c45e4</guid>
            <category><![CDATA[feedback]]></category>
            <category><![CDATA[openweather-api]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[weather-apps]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 12:05:42 GMT</pubDate>
            <atom:updated>2024-08-14T12:05:42.660Z</atom:updated>
            <content:encoded><![CDATA[<p>I was inspired when start my PET project on Nuxt.js and pick up the Weather Application. Found free OpenWeather API, but everything was not so clear, as I dreamed.</p><p>Firstly, my idea was simple — make one-page app, with search input by city name, display the weather and that’s all. However, in the process, I decided that’s too easy. After research, I would to implement drop-down list search, automatic geolocation detection and forecast for few days. At that moment “pandora’s box has opened”. So all step by step.</p><p>Thoughts were: “I can make separate it on two pages. First — will have automatic geolocation detection, where user have possibility to allow it or cancel, and drop-down list search. Second page only weather for today and forecast.”</p><p>My first issue was inconsistency between API for drop-down list search and weather. For drop-down list search I used Geocoding API from OpenWeather API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*ZF6ZL3DzwqUBgZXBTAexpA.png" /></figure><p>I had name of city with lon and lat coordinates, so I could get weather in the current city, using this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*NjsMqa9a06OlvS8AU8d_pg.png" /></figure><p>All was wonderful, before I didn’t notice that some names of the cities doesn’t match. And it’s not because they were renamed, it’s like another city.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*VJIm1vVILI0aOW_94bSwqQ.png" /><figcaption>Somebody will type in search input Lviv, so on the weather person will expect Lviv. Notice that in Ukraine, we have city Lviv, Lvivska Oblast (district) and village Lviv.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*zc7lae1JpAhdUSqcHatZPQ.png" /><figcaption>I used the same lon and lat, but have a different names.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_dmjSaLrA4q90RjRaPhkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*u1MtY4wC5_-ZL95utRoGXw.png" /><figcaption>When I had typed “Artema” in search, it’s nothing in Dnipropetrovska Oblast and coordinates differs.</figcaption></figure><p>That was my first issue with free API, so I take a decision to use name of city and country, like in their example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*NHEoT4d1DmN-kXpxFGIWkw.png" /></figure><p>Second not issue, but like bug, response from API has duplicates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*ug1q5wupxgX1m_4hWfwl2A.png" /><figcaption>When searching Paris we have 3 the same.</figcaption></figure><p>Fix was easy, using Map:</p><pre> async getCityInfo(city) {<br>    const url = `${CITY_URL}${city}&amp;limit=10&amp;appid=${API_KEY}`;<br>    return await axios<br>      .get(url)<br>      .then((response) =&gt; response.data)<br>      .then((info) =&gt; {<br>        if (!info) return [];<br>        const cityInfo = info.map((city) =&gt; ({<br>          city: city.name,<br>          country: city.country,<br>          state: city.state,<br>        }));<br><br>        const uniqueCityInfo = Array.from(<br>          new Set(cityInfo.map(JSON.stringify))<br>        ).map(JSON.parse);<br><br>        return uniqueCityInfo;<br>      })<br>      .catch((err) =&gt; null);<br>  }</pre><p>In conclusion, I could say — just read carefully documentation and make tests on small project to avoid such surprises.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=910b394c45e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-time chat with Socket.io, MongoDB + JWT]]></title>
            <link>https://blog.devgenius.io/real-time-chat-with-socket-io-mongodb-jwt-72cda2d168f1?source=rss-d451829051d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/72cda2d168f1</guid>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[real-time-chat]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[unaGata]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 15:02:53 GMT</pubDate>
            <atom:updated>2024-03-11T17:13:13.290Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@fallen.snitch/simple-real-time-chat-using-socket-io-javascript-part-1-e9c7ad690d77">previous part</a>, we found out how to create real-time chat without using DB. The goal of this article is writing back-end with using MongoDB, tokens and hashing data.</p><p>Firstly, separate Back-End and Front-End. I use folders “client” and “server”.</p><h3>Front-End</h3><p>Create &amp; navigate to the “client” folder, init new project and use next command on a terminal:</p><p>npm install express@4.18.2</p><h3>HTML</h3><p>To implement the new design, let’s use HTML markup from <a href="https://medium.com/@fallen.snitch/simple-real-time-chat-using-socket-io-javascript-part-1-e9c7ad690d77">previous part</a>. Create 3 files: login.html, registration.html and chat.html. We’ll use Bootstrap to style these pages. Below attached result files.</p><p><strong>registration.html</strong></p><pre>&lt;div class=”main-wrapper”&gt;<br>  &lt;ul class=&quot;nav justify-content-end&quot;&gt;<br>    &lt;li class=&quot;nav-item&quot;&gt;<br>      &lt;a class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;/login&quot;&gt;Log in&lt;/a&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br><br>  &lt;div class=&quot;registration-container container d-flex flex-column justify-content-center align-items-center&quot;&gt;<br>    &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; class=&quot;d-none&quot;&gt;<br>      &lt;symbol id=&quot;exclamation-triangle-fill&quot; viewBox=&quot;0 0 16 16&quot;&gt;<br>        &lt;path d=&quot;M8.982 1.566a1.13 1.13 0 0 0–1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98–1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1–1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0–2z&quot;/&gt;<br>      &lt;/symbol&gt;<br>    &lt;/svg&gt;<br><br>    &lt;div id=&quot;error-wrapper&quot;&gt;<br>  &lt;/div&gt;<br><br>  &lt;form id=&quot;registration&quot; class=&quot;row g-3&quot;&gt;<br>      &lt;h2 class=&quot;hedline-login&quot;&gt;Registration&lt;/h2&gt;<br>      &lt;div class=&quot;col-12&quot;&gt;<br>        &lt;label for=&quot;username&quot; class=&quot;form-label&quot;&gt;Username&lt;/label&gt;<br>        &lt;input id=&quot;inputUsername&quot; class=&quot;form-control&quot; type=&quot;text&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;col-12&quot;&gt;<br>        &lt;label for=&quot;inputPassword4&quot; class=&quot;form-label&quot;&gt;Password&lt;/label&gt;<br>        &lt;input id=&quot;inputPassword&quot; class=&quot;form-control&quot; type=&quot;password&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;col-12&quot;&gt;<br>        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Sign up&lt;/button&gt;<br>      &lt;/div&gt;<br>   &lt;/form&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;script src=&quot;https://real-time-p8h4.onrender.com/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;<br>&lt;script defer src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script defer src=&quot;./static/register.js&quot;&gt;&lt;/script&gt;</pre><p><strong>login.html</strong></p><pre>&lt;div class=”main-wrapper”&gt;<br>       &lt;ul class=&quot;nav justify-content-end&quot;&gt;<br>            &lt;li class=&quot;nav-item&quot;&gt;<br>            &lt;a class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;/register&quot;&gt;Create an account&lt;/a&gt;<br>            &lt;/li&gt;<br>        &lt;/ul&gt;<br><br>        &lt;div class=&quot;login-wrapper container d-flex flex-column justify-content-center align-items-center&quot;&gt;<br><br>            &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; class=&quot;d-none&quot;&gt;<br>                &lt;symbol id=&quot;exclamation-triangle-fill&quot; viewBox=&quot;0 0 16 16&quot;&gt;<br>                  &lt;path d=&quot;M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z&quot;/&gt;<br>                &lt;/symbol&gt;<br>            &lt;/svg&gt;<br><br>            &lt;section id=&quot;error-wrapper&quot;&gt;  <br>            &lt;/section&gt;<br><br>            &lt;form id=&quot;login&quot;  class=&quot;row g-3 d-flex flex-column align-items-center w-100&quot;&gt;<br>                &lt;h2 class=&quot;hedline-login col-8&quot;&gt;Log In to Chat&lt;/h2&gt;<br>                &lt;div class=&quot;col-8&quot;&gt;<br>                    &lt;label for=&quot;username&quot; class=&quot;form-label&quot;&gt;Username&lt;/label&gt;<br>                    &lt;input id=&quot;inputUsername&quot; class=&quot;form-control&quot; type=&quot;text&quot;&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-8&quot;&gt;<br>                &lt;label for=&quot;inputPassword4&quot; class=&quot;form-label&quot;&gt;Password&lt;/label&gt;<br>                &lt;input id=&quot;inputPassword&quot; class=&quot;form-control&quot; type=&quot;password&quot;&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;col-8 d-flex justify-content-center&quot;&gt;<br>                    &lt;button class=&quot;btn btn-outline-info btn-lg w-50&quot; type=&quot;submit&quot;&gt;Log In&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;    <br>    &lt;/div&gt;<br><br>    &lt;script src=&quot;http://localhost:5000/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;<br>    &lt;script defer src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script defer src=&quot;./static/login.js&quot;&gt;&lt;/script&gt;</pre><p><strong>chat.html</strong></p><pre>&lt;div id=”chat-container” class=”container “&gt;<br>  &lt;div class=&quot;wrapper d-flex flex-column justify-content-between w-100&quot;&gt;<br>     &lt;ul id=&quot;message-container&quot; class=&quot;d-flex flex-column&quot;&gt;<br>      &lt;/ul&gt;<br><br>      &lt;form class=&quot;message-form__container d-flex  align-items-center w-100&quot; id=&quot;message-form&quot; action=&quot;&quot; method=&quot;&quot;&gt;<br>         &lt;textarea class=&quot;textarea-form&quot; id=&quot;message-input&quot; cols=&quot;2&quot; rows=&quot;3&quot;&gt;&lt;/textarea&gt;<br>         &lt;button class=&quot;btn btn-outline-info btn-lg&quot; type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br><br>&lt;script src=&quot;https://real-time-p8h4.onrender.com/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;<br>&lt;script defer src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script defer src=&quot;./static/chat.js&quot;&gt;&lt;/script&gt;</pre><h3><strong>JavaScript</strong></h3><p>By SRP create own js-files to each of pages: register.js, login.js, chat.js.</p><p><strong>register.js:</strong></p><pre>const server = ‘https://real-time-p8h4.onrender.com&#39;; // here I used server where I deployed app (Render.com)<br><br>axios.defaults.baseURL = server;<br>const usernameInput = document.getElementById(&#39;inputUsername&#39;);<br>const passwordInput = document.getElementById(&#39;inputPassword&#39;);<br>const registrationForm = document.getElementById(&#39;registration&#39;);<br>const errorWrapper = document.getElementById(&#39;error-wrapper&#39;);<br><br><br>registrationForm.addEventListener(&#39;submit&#39;, e =&gt; {  <br>    e.preventDefault();<br>    let username = usernameInput.value;<br>    let password = passwordInput.value;<br><br>    axios.post(&#39;auth/register&#39;, {username: username, password: password}) //send data and generate token at our backend<br>    .then((response) =&gt; {<br>        localStorage.setItem(&#39;token&#39;, response.data.token);<br>        location = &#39;/&#39;<br>    })<br>    .catch(error =&gt; {<br>        errorWrapper.innerHTML = `<br>        &lt;div class=&quot;alert w-100 alert-danger d-flex align-items-center&quot; role=&quot;alert&quot;&gt;<br>            &lt;svg class=&quot;bi danger-img&quot; role=&quot;img&quot; aria-label=&quot;Danger:&quot;&gt;<br>                &lt;use xlink:href=&quot;#exclamation-triangle-fill&quot;/&gt;<br>            &lt;/svg&gt;<br>             <br>            &lt;div&gt;<br>                ${error.response.data.message}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        `<br>    })<br>})</pre><p><strong>login.js:</strong></p><pre>const server = ‘https://real-time-p8h4.onrender.com&#39;;<br><br>axios.defaults.baseURL = server;<br>const usernameInput = document.getElementById(&#39;inputUsername&#39;);<br>const passwordInput = document.getElementById(&#39;inputPassword&#39;);<br>const loginForm = document.getElementById(&#39;login&#39;);<br>const errorWrapper = document.getElementById(&#39;error-wrapper&#39;);<br><br><br>loginForm.addEventListener(&#39;submit&#39;, e =&gt; {<br>    e.preventDefault();<br>    let username = usernameInput.value;<br>    let password = passwordInput.value;<br><br>    axios.post(&#39;auth/login&#39;, {username: username, password: password})<br>    .then((response) =&gt; {<br>        localStorage.setItem(&#39;token&#39;, response.data.token);<br>        location = &#39;/&#39;<br>    })<br>    .catch(error =&gt; {<br>        errorWrapper.innerHTML = `<br>        &lt;div class=&quot;alert w-100 alert-danger d-flex align-items-center&quot; role=&quot;alert&quot;&gt;<br>            &lt;svg class=&quot;bi danger-img&quot; role=&quot;img&quot; aria-label=&quot;Danger:&quot;&gt;<br>                &lt;use xlink:href=&quot;#exclamation-triangle-fill&quot;/&gt;<br>            &lt;/svg&gt;<br>             <br>            &lt;div&gt;<br>                ${error.response.data.message}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        `<br>    })<br>})</pre><p><strong>chat.js:</strong></p><pre>const token = localStorage.getItem(‘token’); //check is token exist<br><br>if (!token){<br>    location = &#39;/register&#39;<br>}<br>const server = &#39;https://real-time-p8h4.onrender.com&#39;;<br>axios.defaults.baseURL = server;<br>const msgFromMeClass = &#39;message--from-me&#39;;<br>const msgSystemClass = &#39;message--system&#39;;<br><br>const decoded = decodeJWT(token);<br>const username = decoded.payload.username;<br>const socket = io (server, {<br>    query: {token}<br>});;<br><br>axios.get(&#39;/msgs/getAll&#39;)<br>    .then(resp =&gt; resp.data)<br>    .then(messages =&gt;{<br>        for (const msg of messages) {<br>            const addingClass = username === msg.username ? msgFromMeClass : &#39;&#39;;<br>            renderMessage(msg.username, msg.message, addingClass);<br>        }<br>    })<br><br><br>const messageContainer = document.getElementById(&#39;message-container&#39;);<br>const messageForm = document.getElementById(&#39;message-form&#39;);<br>const messageInput = document.getElementById(&#39;message-input&#39;);<br>const chatContainer = document.getElementById(&#39;chat-container&#39;);<br>const usernameEl = document.getElementById(&#39;username&#39;);<br><br>socket.on(&#39;user-connected&#39;, data =&gt; {<br>    renderMessage(&#39;SYSTEM&#39;, `${data} connected`, msgSystemClass)<br>});<br><br>socket.on(&#39;output-messages&#39;, data =&gt; {<br>    console.log(data)<br>})<br><br>socket.on(&#39;chat-message&#39;, data =&gt; {<br>    const addingClass = username === data.username ? msgFromMeClass : &#39;&#39;;<br>    renderMessage(data.username, data.message, addingClass);<br>});<br><br>socket.on(&#39;user-disconnected&#39;, data =&gt; {<br>    renderMessage(&#39;SYSTEM&#39;, `${data} disconnected`, msgSystemClass)<br>});<br><br>messageForm.addEventListener(&#39;submit&#39;, handleSubmit);<br>messageInput.addEventListener(&#39;keydown&#39;, handleSubmit);<br><br>function handleSubmit(e) {<br>    if (e.key === &#39;Enter&#39; || e.type === &#39;submit&#39;) {<br>      e.preventDefault();<br>      const message = messageInput.value;<br>      if (!message.trim()) return;<br>      socket.emit(&#39;send-chat-message&#39;, message);<br>      messageInput.value = &#39;&#39;;<br>    }<br>}<br><br><br>function renderMessage(from, message, className){<br>    messageContainer.innerHTML += `  <br>    &lt;li class=&quot;${className}&quot;&gt;<br>        &lt;div class=&quot;message&quot;&gt;<br>            &lt;span class=&quot;author&quot; style=&quot;font-size: 70%;&quot;&gt;${from}&lt;/span&gt;<br>            &lt;span class=&quot;message-text&quot;&gt;${message}&lt;/span&gt;<br>        &lt;/div&gt;<br>    &lt;/li&gt;<br>    `;<br>    messageContainer.scrollTop = messageContainer.scrollHeight;<br>}<br><br>function base64UrlDecode(base64Url) {  //decode the payload of JWT to get information about user<br>    let padding = &#39;=&#39;.repeat((4 - (base64Url.length % 4)) % 4);<br>    let base64 = (base64Url + padding).replace(/-/g, &#39;+&#39;).replace(/_/g, &#39;/&#39;);<br>    return atob(base64);<br>}<br>  <br>function decodeJWT(token) {<br>  const [headerEncoded, payloadEncoded, signature] = token.split(&#39;.&#39;);<br>  const header = JSON.parse(base64UrlDecode(headerEncoded));<br>  const payload = JSON.parse(base64UrlDecode(payloadEncoded));<br>  <br>  return { header, payload, signature };<br>}<br><br></pre><p>Set up a basic Express.js server on client side in <strong>index.js</strong> file<strong>:</strong></p><pre><br>const express = require(‘express’);<br><br>const app = express();<br>const port = process.env.PORT || 3000; <br>const srcDirname = __dirname + &#39;/src&#39;<br>app.use(&#39;/static&#39;, express.static(srcDirname + &#39;/static&#39;));<br><br><br>app.get(&#39;/login&#39;, (req, res) =&gt; {<br>  res.sendFile(srcDirname + &#39;/login.html&#39;);<br>});<br><br>app.get(&#39;/register&#39;, (req, res) =&gt; {<br>  res.sendFile(srcDirname + &#39;/register.html&#39;);<br>});<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.sendFile(srcDirname + &#39;/chat.html&#39;);<br>});<br><br><br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on port ${port}`);<br>});<br><br></pre><h3>Back-end</h3><p>Navigate to the “service” folder, init new project and use next command on a terminal to install dependencies:</p><pre>npm install bcryptjs@^2.4.3<br>npm install cors@^2.8.5<br>npm install express@^4.18.2<br>npm install express-validator@^7.0.1<br>npm install jsonwebtoken@^9.0.2<br>npm install mongoose@^7.5.2<br>npm install nodemon@^3.0.1<br>npm install socket.io@^4.7.2</pre><ol><li><strong>bcryptjs </strong>— for hashing passwords.</li><li><strong>cors </strong>— Cross-Origin Resource Sharing middleware for Express.js. It enables secure cross-origin resource sharing.</li><li><strong>express</strong> — a web application framework for Node.js. Also it simplifies the process of building web applications and APIs.</li><li><strong>express-validator</strong> -for validation</li><li><strong>jsonwebtoken</strong> — for creating and verifying JSON Web Tokens (JWTs). Used for secure authentication between parties.</li><li><strong>mongoose</strong> — library for MongoDB and Node.js. It provides a higher-level abstraction for interacting with MongoDB.</li><li><strong>nodemon</strong> — a utility that monitors for changes in Node.js application and automatically restarts the server.</li><li><strong>socket.io</strong> — for real-time chating.</li><li><strong>postman</strong> — check working back-end or not</li></ol><p>Next step to make structure like this for better navigation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*LBTfRWntI_CNdHFsvTvQrA.png" /></figure><p>Delve into index.js file:</p><pre>import express from &quot;express&quot;;<br>import mongoose from &quot;mongoose&quot;;<br><br>import { createServer } from &quot;node:http&quot;;<br>import { Server } from &#39;socket.io&#39;;<br><br>const PORT = process.env.PORT || 5000;<br>const DB_URL = `Here you write your URL, which you can get from Mongo DB`;</pre><p>Creating server:</p><pre>const app = express();<br>const httpServer = createServer(app);<br><br>app.use(express.json());<br><br><br>async function startApp(){<br>    try{<br>        await mongoose.connect(DB_URL)<br>        httpServer.listen(PORT, () =&gt; console.log(&#39;SERVER WORKS ON PORT &#39; + PORT));<br>    } catch (e){<br>        console.log(e)<br>    }<br>}<br><br>startApp();</pre><p>Connecting to the DB:</p><pre>mongoose.connect(DB_URL, {useUnifiedTopology: true, useNewUrlParser: true}).then(() =&gt; {<br>    console.log(&#39;connected&#39;)<br>}).catch(err =&gt; console.log(err))</pre><p>Return to “models” folder and implement next Scheme for Message.js and User.js to describe cooperation with Mongo.DB:</p><ol><li><strong>User.js</strong>:</li></ol><pre>import mongoose from &quot;mongoose&quot;;<br><br>const User = new mongoose.Schema({  // describe how you would to put data on the mongo server<br>    username: {type: String, unique: true, required: true},<br>    password: {type: String, required: true}  <br>})<br><br>export default mongoose.model(&#39;User&#39;, User)</pre><p>2. <strong>Message.js</strong>:</p><pre><br>import mongoose from &quot;mongoose&quot;;<br><br>const Message = new mongoose.Schema({ <br>    userId: {type: String}, // mongo will automaticly create id for user and we can used it<br>    username: {type: String, required: true},<br>    message: {type: String, required: true}, <br>})<br><br>export default mongoose.model(&#39;Message&#39;, Message)</pre><p>At your DB it would look like (more about <a href="https://www.mongodb.com/docs/atlas/app-services/schemas/#schemas"><strong>Schemas</strong></a><strong>)</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*wyiORl1sKzaNMwlJQ1J0VA.png" /></figure><p>Next step, create middleware in <strong>authRouter.js</strong>:</p><pre>import { Router } from &quot;express&quot;;<br>import authController from &quot;../controllers/authController.js&quot;;  //after midleware creating Class<br>import { check } from &quot;express-validator&quot;<br><br>const router = new Router();<br><br><br>router.use(function(req, res, next) {  //check CORS<br>    res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);<br>    res.header(&quot;Access-Control-Allow-Headers&quot;, &quot;Origin, X-Requested-With, Content-Type, Accept&quot;);<br>    next();<br>});<br>router.post(&#39;/register&#39;, [<br>    check(&#39;username&#39;, &quot;This field couldn&#39;t be empty&quot;).notEmpty(), //make validation<br>    check(&#39;password&#39;, &quot;Password must be not less than 4 symbols&quot;).isLength({min: 4})<br>], authController.register);<br><br>router.post(&#39;/login&#39;, [<br>    check(&#39;username&#39;, &quot;This field couldn&#39;t be empty&quot;).notEmpty()<br>], authController.login);<br>router.get(&#39;/users&#39;, authController.getUsers);<br><br>export default router;</pre><p>Connect middleware in <strong>index.js</strong>:</p><pre>import authRouter from &quot;./routers/authRouter.js&quot;;<br><br>app.use(&#39;/auth&#39;, authRouter);</pre><p>In <strong>authController.js </strong>describe how interact with user, validate and use tokens for security:</p><pre>import User from &quot;../models/User.js&quot;;<br>import { validationResult } from &quot;express-validator&quot;;<br>import jwt from &quot;jsonwebtoken&quot;;<br>import { secret } from &quot;../config.js&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br><br>const generateAccessToken = (id, username, password) =&gt; {<br>    const payload = {<br>        id,<br>        username, <br>        password<br>    }<br>    return jwt.sign(payload, secret, {expiresIn: &quot;12h&quot;})  // create secret key<br>}<br><br></pre><p>In <strong>config.js</strong>, create random key, which will know only our server:</p><pre>export const secret = &quot;SECRET_KEY_RANDOM&quot;;</pre><p>Continue in <strong>authController.js</strong>:</p><pre>class authController {<br>    async register(req, res){<br>        try{<br>            const erorrs = validationResult(req);<br>            if(!erorrs.isEmpty()){<br>                return res.status(400).json({message: &quot;Username or password is not correct&quot;, erorrs})<br>            }<br>            const { username, password } = req.body;  //get data<br>            const isUser = await User.findOne({username}); //check is user exsist<br>            if(isUser){<br>                return res.status(400).json({message: &#39;This user is already registered&#39;})<br>            }<br>            const hashPassword = bcrypt.hashSync(password, 7);  //hahs password <br>            const user = new User({username, password: hashPassword});<br>            await user.save();<br>            const token = generateAccessToken(user._id, user.username, user.password);<br>            return res.json({token})<br>        } catch(e){<br>            res.status(400).json({message: &#39;Something went wrong&#39;});<br>        }<br>    }<br><br>    async login(req, res){<br>        try{<br>            const { username, password } = req.body;<br>            const user = await User.findOne({username});<br>            if(!user){<br>                return res.status(400).json({message: `User ${username} is not found`})<br>            } <br>            const validPassword = bcrypt.compareSync(password, user.password); //checking password<br>            if(!validPassword){<br>                return res.status(400).json({message: `Password  is incorrect`})<br>            }<br>            const token = generateAccessToken(user._id, user.username,user.password);<br>            return res.json({token})<br>        } catch(e){<br>            res.status(400).json({message: &#39;Login erorr&#39;});<br>        }<br>    }<br><br>  <br>}<br><br>export default new authController();</pre><p>To check works our service or not use <a href="https://www.postman.com/"><strong>Postman</strong></a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0lRcPHeeLBbAzTb9EDA2A.png" /></figure><p>Provide same logic for Messages in <strong>messageRouter.js</strong>:</p><pre>import { Router } from &quot;express&quot;;<br>import MsgController from &quot;../controllers/msgController.js&quot;;<br><br>const router = new Router();<br>router.use(function(req, res, next) {<br>    res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);<br>    res.header(&quot;Access-Control-Allow-Headers&quot;, &quot;Origin, X-Requested-With, Content-Type, Accept&quot;);<br>    next();<br>});<br>router.get(&#39;/getAll&#39;, MsgController.getAll);<br><br>export default router;<br><br><br>In msgController.js I used only getAll(), because I don&#39;t plan to extend it:   import Message from &quot;../models/Message.js&quot;;<br><br>class MsgController {<br>    async getAll(req, res){<br>        try{<br>            res.json(await Message.find({}))<br>        } catch(e){<br>            res.status(400).json({message: &#39;Erorr&#39;});<br>        }<br>    }<br>}<br><br>export default new MsgController();</pre><p>Return to our index.js file to import message midllware:</p><pre>import messageRouter from &quot;./routers/messageRouter.js&quot;;<br>import cors from &#39;cors&#39;; <br>import Message from &quot;./models/Message.js&quot;;<br>import { secret } from &quot;./config.js&quot;;<br>import jwt from &quot;jsonwebtoken&quot;;<br><br>Configurate CORS: <br><br>const corsHeaders = {<br>    &#39;Access-Control-Allow-Origin&#39;: &quot;*&quot;,<br>    &#39;Access-Control-Allow-Methods&#39;: &#39;GET,PUT,POST,DELETE&#39;,<br>    &#39;Access-Control-Allow-Headers&#39;: &#39;Content-Type&#39;<br>};<br><br><br>app.use(&#39;/auth&#39;, authRouter);<br>app.use(&#39;/msgs&#39;, messageRouter);<br>app.use(cors());<br>app.use(allowAnyCORS);<br><br><br>function allowAnyCORS (req, res, next) {<br>    for(let header in corsHeaders){<br>        req.header(header, corsHeaders[header]);<br>        res.header(header, corsHeaders[header]);<br>    }<br>    next();<br>}</pre><p>We have the same main logic for message exchange:</p><pre>io.use(function(socket, next){ //make small autentification <br>    if (socket.handshake.query &amp;&amp; socket.handshake.query.token){<br>      jwt.verify(socket.handshake.query.token, secret, function(err, decoded) {<br>        if (err) return next(new Error(&#39;Authentication error&#39;));<br>        socket.decoded = decoded;<br>        next();<br>      });<br>    }<br>    else {<br>      next(new Error(&#39;Authentication error&#39;));<br>    }    <br>})<br>.on(&#39;connection&#39;, function(socket) {  track connection<br>    socket.broadcast.emit(&#39;user-connected&#39;, socket.decoded.username);<br>    socket.emit(&#39;user-connected&#39;, socket.decoded.username)<br><br><br>    socket.on(&#39;send-chat-message&#39;, (message) =&gt; { process event of sending massage<br>        const msg =  new Message({ userId: socket.decoded.id, username: socket.decoded.username, message: message });<br>        msg.save() <br>        .then((result) =&gt; {<br>            socket.broadcast.emit(&#39;chat-message&#39;, { username: socket.decoded.username, message: message });<br>            socket.emit(&#39;chat-message&#39;, { username: socket.decoded.username, message: message });<br>        })<br>        .catch((err) =&gt; {<br>            console.log(&#39;err&#39;, err)<br>        })<br>    });<br><br>    socket.on(&#39;disconnect&#39;, function() {   track disconnect<br>        socket.broadcast.emit(&#39;user-disconnected&#39;, socket.decoded.username);<br>    });<br><br>})</pre><p>And it’s done. We have our first Real-time chat. Hope this information was usseful.</p><p>Link for style.css <a href="https://github.com/soyUnaGata/real_time_chat_mongodb/blob/origin/clientv2/src/static/style.css"><strong>here</strong></a></p><p>My Real-time chat<strong> </strong><a href="https://real-time-client.onrender.com/register"><strong>here</strong></a></p><p>Share in comments yours Real-time projects to help each other grow and develop!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72cda2d168f1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/real-time-chat-with-socket-io-mongodb-jwt-72cda2d168f1">Real-time chat with Socket.io, MongoDB + JWT</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>