<?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 Karthick Ragavendran on Medium]]></title>
        <description><![CDATA[Stories by Karthick Ragavendran on Medium]]></description>
        <link>https://medium.com/@karthickragavendran?source=rss-1dc8778cadf0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*yxGbCRonEqNTr6H05sqBvQ.jpeg</url>
            <title>Stories by Karthick Ragavendran on Medium</title>
            <link>https://medium.com/@karthickragavendran?source=rss-1dc8778cadf0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:12:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karthickragavendran/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[The Crayon Will]]></title>
            <link>https://karthickragavendran.medium.com/the-crayon-will-e152dd6de6a9?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e152dd6de6a9</guid>
            <category><![CDATA[short-story]]></category>
            <category><![CDATA[war]]></category>
            <category><![CDATA[fiction]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 08:51:39 GMT</pubDate>
            <atom:updated>2024-10-04T14:36:34.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Crayon Will</h3><p>The hospital was half-ruined — dusty walls, cracked floors, and broken windows surrounded the place. Distant sounds of bombs and planes echoed through the air. A young boy lay in a small corner of the hospital. He had no one left — no family, no friends — only a ball. Every day, he held it close to his chest like a shield against the dangerous world.</p><p>His body was weak and thin. A wound on his leg from the last airstrike troubled him. The hospital had no medicines left. Everyone tried to stay hopeful, but it was hard.</p><p>Every morning, the doctor walked in for check-ups. He was a kind man with tired eyes but a warm smile. He examined the boy’s leg, looked into his eyes, and said, “You’ll get better soon. Don’t worry.”</p><p>He handed the boy a small cup of plain water poured from a syrup bottle. “Here, drink this medicine. It will help you feel strong,” he said. The boy drank it, believing the doctor’s words.</p><p>As the doctor was leaving, he noticed the ball. “Ah, your ball!” he said with a smile. “One day, we’ll play with it together.” The boy nodded, holding his ball a little tighter. For a moment, the room felt brighter.</p><p>The days were long. The boy often lay on his bed, staring at the cracks in the ceiling, holding his ball close. The doctor’s promise to play with him kept him smiling, even when the pain in his leg made him wince.</p><p>One hot afternoon, the boy woke up suddenly from a nightmare. His hand reached for his ball — his companion, but it was not there. His heart raced. He sat up quickly, searching under the blanket, beside his bed, everywhere he could reach — but the ball was gone.</p><p>His eyes scanned the room, and then he saw it. In the bed next to him, a little boy was playing with his ball. Beside the little boy sat his sister, about the same age as him. Her legs were wrapped in dirty bandages, and she looked tired. The little boy was gently bouncing the ball on the floor, a soft smile on his face.</p><p>“Hey…” the boy called out. His voice was shaky, a mix of anger and fear. The little boy froze, eyes wide like a deer caught in headlights. Slowly, he looked up, scared. The boy pointed to the ball with trembling fingers. “That’s my ball,” he said softly but firmly.</p><p>The little boy didn’t argue. He picked up the ball and, with slow, careful steps, walked over to the boy’s bed. Without saying a word, he placed the ball in the boy’s hand.</p><p>“Don’t touch my ball,” the boy said.</p><p>The little boy nodded, then quietly turned away and went back to sit beside his sister.</p><p>The boy felt relieved to have his ball back, but he couldn’t ignore the sadness in the little boy’s eyes. They were just like his own — tired, frightened, and alone.</p><p>The boy’s thoughts drifted back to the day his mother gave him the ball. He remembered walking through the market, holding her hand. With the threat of war looming, jobs were scarce, and they were struggling for money.</p><p>“Mom, ball?” he had asked, pointing to a bright, shiny ball in a stall. He already knew what she would say — she would say no. He braced himself to protest.</p><p>His mother shook her head gently. “Maybe another time,” she said.</p><p>He stopped walking, sat down right there in the middle of the road, and let the tears fall. “Leave me here! I won’t come with you!”</p><p>His mother sighed but didn’t leave him behind. She picked him up, cradled him in her arms, and carried him home, his cries echoing through the streets. Back at home, he sat alone, sulking, his face buried in his hands.</p><p>Determined, his mother began searching the house, looking for coins tucked away in drawers and under cushions. After gathering a small handful, she came to him and asked softly, “Are you coming?”</p><p>He was still angry and refused to go. She left without another word, but as time passed, the boy grew restless. He stepped outside, pacing up and down the street, waiting, hoping. And then he saw her — walking toward him, holding the ball in her hand.</p><p>He ran to her, his anger forgotten. He grabbed the ball, tossing it up and down, laughing as he ran circles around her.</p><p>The memory faded, leaving a deep longing in his heart and a tear rolling down his cheek. He felt a pang of guilt for making her go through all that trouble. “I’m sorry,” he whispered to the darkness.</p><p>In the middle of the night, the boy woke up gasping, another nightmare pulling him out of sleep. The room felt stifling, and his breaths came quick and shallow. He reached for his ball, holding it close, hoping it would calm him. But his is fingers touched only the blanket.</p><p>The ball was gone.</p><p>Panic surged through him like a wave. The ward was dark, only a faint glow of moonlight spilling through the shattered windows. He frantically searched his bed, tossing the thin sheet aside. His eyes darted to the nearby bed, where the little boy lay sleeping next to his sister.</p><p>“Hey!” he called out, his voice sharp and loud. But the little boy didn’t wake. He shouted again, louder, his desperation cutting through the stillness of the ward.</p><p>A few of the other patients stirred, annoyed murmurs filling the silence. But he didn’t care. He needed his ball back.</p><p>Desperate, the boy reached down, grabbing a small broken stone from the crumbling wall beside his bed. Without thinking, he hurled it at the little boy, and it struck his forehead. The little boy woke with a cry, clutching his head, eyes wide and terrified.</p><p>“Don’t act! Where is my ball?” the boy shouted, his voice cracking with fear. “Thief! Give me my ball back!”</p><p>The little boy sat up, confused and frightened, shaking his head as if trying to understand what was happening. He got to his feet, stumbling in the darkness. His small hands moved frantically, lifting blankets and groping under beds. The faint moonlight barely helped, and he struggled to see as he crawled on his knees between the cots of sleeping patients, his fingers brushing over the cold floor.</p><p>The boy’s anxiety grew with every second that passed. The fear gnawed at him — he couldn’t bear the thought of losing it forever. “Where did you hide the ball? Did you take it outside? Someone will steal it!” he cried out, his voice rising, frantic. “Give me my ball back! Thief!”</p><p>The boy’s voice trembled in the darkness of the ward. “They can’t even find missing people,” he whispered, his words barely audible. “Where will I go and search for my ball?” He paused, his breath catching in his throat. The reality of his situation began to sink in, and his next words came out in a choked sob. “My legs are also broken. How can I look for it?” The thought overwhelmed him, and he broke down completely. His cries echoed through the dark ward, growing louder with each passing moment. “I… I have no one else,” he wailed, his small body shaking with each sob. More patients stirred in their beds, awakened by the boy’s distress. His grief consumed him entirely. In that moment, the missing ball seemed to represent everything he had lost — his home, his family, his ability to move freely. It was all gone, just like his beloved ball.</p><p>The little boy’s sister stirred awake from the commotion, rubbing her eyes as she tried to adjust to the darkness of the ward. She squinted, searching for her brother’s ball, but everything was just shadows and shapes.</p><p>Then, a faint flash flickered outside, barely brightening the room. A missile had struck far away, just close enough to send a ripple of light through the darkness.</p><p>In that fleeting moment of light, the sister’s eyes spotted the ball, half-hidden beneath the cot of an old man across the room. She nudged her brother urgently, pointing toward it. Seconds later, a dull, distant boom echoed through the walls.</p><p>The little boy quickly crawled over, reaching under the cot. He grasped the ball, then walked back slowly, holding it out to the boy with trembling hands, his eyes fixed on the ground.</p><p>The boy snatched the ball roughly from the little boy’s hands and curled up on his bed, clutching it tightly to his chest. He kissed it, feeling the familiar smoothness against his skin. It felt like finding a lost pet.</p><p>The little boy returned to his sister, curling up beside her like a frightened puppy. The ward settled back into a tense quiet, the heavy breathing of sleeping patients the only sound.</p><p>The boy sat on his bed, gripping his ball, feeling his anger slowly slip away, leaving behind a heavy emptiness. He glanced at the little boy, who lay with his back to him, holding his sister’s hand for comfort. Guilt washed over him, settling like a stone in his chest. The little boy didn’t deserve this.</p><p>The next morning, he woke up late. He glanced at the bed beside him. Instead of the little boy and his sister, there was a middle-aged lady sleeping with her back turned. No goodbyes, no last look — just strangers where they used to be. He reached for his ball, holding it close as he stared at the bed, now so different.</p><p>Soon, the doctor walked in, attempting a smile. He examined the boy’s wound — it was red, hot, and starting to rot. The boy’s eyes followed every movement, searching the doctor’s face for some sign of hope. But the doctor, who had seen thousands die, couldn’t hide his tears as he watched a child’s leg rotting under his care.</p><p>“It hurts,” the boy whispered.</p><p>“I know,” the doctor replied gently.</p><p>“Not just the leg.” The boy touched his stomach, moved his hand to his chest, then his throat, and finally pointed to his head. The doctor realized the infection was spreading — too quickly. It was preventable, even curable, but there was no medicine.</p><p>“Here,” the doctor said, handing him a cup of plain water from an old syrup bottle, forcing a smile. “Drink this.”</p><p>The boy took the cup and sipped slowly. He hugged his ball to his chest, eyes fixed on the empty bed where the little boy used to sleep.</p><p>The doctor placed a hand on the boy’s shoulder, trying to keep his voice light. “You’ll be better soon. The medicine will come any day now… And then we’ll play with the ball.”</p><p>The boy nodded but stayed silent, staring at the bed where the little boy and his sister used to sleep. He wondered why he never played with them.</p><p>He remembered how the little boy would hold onto the ball when handing it back, holding it just a moment longer. Why hadn’t he let him keep it for a bit longer?</p><p>Now, he felt a deep regret, knowing he’d never see them again.</p><p>The doctor sat in a small corner of the hospital, surrounded by scattered papers and lists. The medical supply was supposed to arrive yesterday, but now the sun was setting, and the entrance to the hospital remained empty.</p><p>Frustration clawed at his chest. He couldn’t wait any longer. With a heavy sigh, he grabbed his cycle and rode toward the main medical center, 7 kilometers away, hoping to find the vital medicines they needed. As he pedaled through the ruined streets, dust clouded the air, and distant echoes of explosions followed him like shadows. He kept riding, pushing against the weight of exhaustion and helplessness.</p><p>At the medical center, hope gave way to despair. Their shelves were empty.</p><p>“What happened?” the doctor asked, his voice barely a whisper.</p><p>The old man shook his head, eyes downcast. “An airstrike hit the supply trucks,” he said softly. “All the medicine was destroyed. We’ll have to wait… maybe next week.”</p><p>“Why do they keep attacking medical supplies?” the doctor asked, his voice trembling.</p><p>The old man remained silent.</p><p>With a heavy heart and empty hands, the doctor returned to the hospital.</p><p>That night, the hospital buzzed with fear. A warning came — another airstrike was heading their way. The doctor stayed the night in the hospital. All lights were off; everyone was silent, waiting.</p><p>Soon, the roar of missiles began. Explosions lit up the sky, shaking the walls. The boy gripped his ball tightly against his chest, squeezing his eyes shut. The sounds outside were loud, deafening, but to the boy, they slowly faded away. His body felt heavy and numb, and he sank into his dreams.</p><p>In his dream, he was back in his old home, sitting around a table with his mother, father, and siblings. The familiar spices of dinner filled the air — soft rice, warm bread, fresh curry. Laughter echoed through the room. His mother smiled, her eyes shining like they used to. His father’s gentle hand ruffled his hair. His elder brother and sister joked as they passed food to each other. It was pure joy, full of love and safety.</p><p>He reached out to touch his mother’s hand, but suddenly, the dining table began to shake. The rumble of bombs grew louder, the missiles hitting the hospital in real life.</p><p>He didn’t want to wake up. He shut his ears and shouted, “Mom!”</p><p>The whole house trembled, but his family didn’t seem to notice. The noise was too loud, shaking everything around him. Then, his mother opened her arms, smiling softly. “Come here,” she said.</p><p>The boy ran to her and hugged her tightly. She held him close, rocking him slowly, and began to sing a familiar lullaby. Gradually, the sounds of the bombs faded away. The melody of his mother’s voice brought him peace.</p><p>The war, the explosions, the shaking, the pain — all of it disappeared.</p><p>The hospital survived the night. The next morning, the doctor prepared for his rounds. He poured plain water into the syrup bottle and walked through the ward, offering sips and gentle words.</p><p>As he approached the boy’s bed, an old man from a nearby cot murmured softly, “Doctor, I think the boy is gone.”</p><p>The doctor turned to see the boy, lying so still hugging his favorite ball, as if simply asleep. His heart clenched. Kneeling beside the bed, he touched the boy’s hand — cold and stiff. He placed his fingers on the boy’s neck, searching for a pulse.</p><p>There was none.</p><p>The ward fell into a deeper silence. A sadness hung in the air, heavy and unmoving.</p><p>As they began to tend to the boy’s body, a nurse found a small folded piece of paper in the boy’s shirt pocket. She carefully unfolded it, and her eyes softened as she read. She handed it to the doctor.</p><p>The note, written in wobbly letters with the crayon the doctor had given him when he first arrived with a non-fatal injury, read:</p><p>“<em>Please give my ball to the boy in bed next to me last week with his sister. To the boy: I’m sorry I wasn’t nice. Please play with my ball. Take care of it.</em>”</p><p>The words echoed through the room, a final message from one child to another.</p><p>It took a few weeks, but the doctor eventually found the little boy and his sister. They were staying in a crowded shelter nearby. The doctor sat with them, the ball and note in his hands. The little boy stared at the doctor’s face, then at the ball.</p><p>“This was from your friend at the hospital,” the doctor said gently. He handed the ball to the little boy, who took it with trembling hands. The little boy looked down at the familiar, worn ball, holding it close.</p><p>“He wanted you to have it,” the doctor continued, handing over the note.</p><p>The sister read the message silently. Her lips pressed together as she fought back tears. She looked at her brother, then back at the doctor. “Thank you,” she whispered.</p><p>“Don’t you want to play with it?” the doctor asked the little boy.</p><p>“He will, after you leave. He’s a bit shy,” the sister said with a small smile. The little boy cuddled his sister, holding the ball.</p><p>As the doctor walked away, he glanced back one last time. The little boy had started to play with it alongside his sister. They bounced it gently between them, small smiles appearing on their faces despite everything around them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkY_FKTAydQqhauDGC0nDA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e152dd6de6a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Butter Bun]]></title>
            <link>https://karthickragavendran.medium.com/the-butter-bun-5e575decbe1c?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e575decbe1c</guid>
            <category><![CDATA[short-story]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 11:53:50 GMT</pubDate>
            <atom:updated>2025-01-19T12:09:51.662Z</atom:updated>
            <content:encoded><![CDATA[<p>The boy’s stomach growled as he walked home from school. He tried to ignore it, keeping his eyes on the dusty road. But as he turned the corner, a sweet smell made him stop.</p><p>There, right after the corner, was the old bakery. Through the window, he could see trays of fresh bread and sweets. His eyes fixed on one tray in particular.</p><p>Butter buns. They sat in neat rows, golden and round. A thin layer of sugar sparkled on top. He knew that inside, there would be a dollop of creamy butter.</p><p>The boy stood still, imagining how they would taste. Soft and warm, sweet and rich. His mouth watered.</p><p>He had no money to buy one.</p><p>The baker came out, wiping flour from his hands. Startled, the boy blushed and hurried away. But the image of those butter buns stayed with him as he walked home.</p><p>That night, dinner was a simple affair. His mother divided what was left into small portions. Supplies were running low, and the next market trip wasn’t until the weekend. He ate slowly, taking small bites. His younger sister had finished her food quickly and was now eyeing his plate, her appetite unusually large that day. He quietly slid his plate over to her, and they shared a small smile.</p><p>The next morning, the kitchen was still bare. Breakfast was nothing more than a glass of water. His mother packed his tiffin with a brief, tired smile, knowing it wasn’t much. He set off for school, ignoring the dull ache in his stomach.</p><p>The afternoon sun made his empty stomach ache even more. His hands shook a little as he reached for his bag, eager to open his tiffin. His fingers searched every corner of the bag, touching books and papers, but not finding the familiar box. His heart began to race. He looked inside again, moving everything around. The box wasn’t there.</p><p>He looked around, panic rising in his chest. Then he saw them — the other boys in the corner, laughing and wiping their mouths. They had taken his food, emptied it without a second thought, treating it as a joke.</p><p>He drank glasses of water hoping it would fill the void. The hot afternoon classroom seemed to spin around him, the teacher’s words blurred. His head felt heavy, and he fought to keep his eyes open.</p><p>The bell rang. As he stood, the classroom tilted briefly before steadying. He made his way to the gate. Near the main road, he saw a car — a shiny, expensive one — pull up nearby. A window rolled down, and a hand emerged, adorned with gleaming rings and bangles that caught the shade.</p><p>The children, sensing food was coming, rushed towards the car in excitement.</p><p>A single finger rose from the window — imperious, manicured — stopping the children in their tracks. The hand ordered them to lower their hands, hovering always at a careful distance that prevented any possibility of touch.</p><p>A small girl at the front hesitantly lowered her palm, cupping it. The bejeweled fingers, satisfied with the distance, delicately dropped a bun into the child’s waiting hands. One by one, the children approached, repeating this careful dance of giving and receiving.</p><p>As more eager faces gathered, the hand grew impatient. The fingers began tossing the buns onto the dusty road, rings catching light with each throw as children scrambled to collect them from the ground.</p><p>The hand found a game in this — tossing the buns higher, farther, watching the children run and jump. Sometimes the fingers would pause, holding a bun in the air just to see small hands reach up, before throwing it in the opposite direction.</p><p>The bangles jingled with delight at each toss.</p><p>The boy stood at the edge, watching the others rush about. His stomach growled, but something held him back.</p><p>The hand paused in its motion, as if noticing the boy who hadn’t rushed forward. It picked up a bun and tossed it in his direction. He watched it soar up through the air, but his feet stayed rooted to the spot. His hands remained at his sides, refusing to move. The bun hit the ground in front of him, sending up a small cloud of dust.</p><p>The hand hung suspended in the air, its stillness somehow commanding: “Go on, take it.” The boy had never seen a gesture so absolute — fingers that expected obedience, that didn’t understand the word “no.” A chill ran through him.</p><p>He looked at the bun lying at his feet. It looked soft and sweet, with butter peeking out from the middle. The world around him seemed to go quiet as if waiting for his decision. His stomach cried out for the bun, but something deeper inside him spoke louder.</p><p>The boy refused to bend down. He took a step back.</p><p>With an irritated gesture, the hand thrust out the window. Bangles jingled as a finger jabbed at him, then at the bun on the ground ordering “Take it!”</p><p>The boy stood his ground.</p><p>The finger jabbed again, more urgent now, its rings flashing like angry eyes. But with each command of the hand, the boy’s spine grew a little straighter.</p><p>He stared at those commanding fingers, so cold and demanding, opposite to his mother’s warm, work-worn hands.</p><p>The hand froze, its earlier playful energy replaced by the strangeness of a puppet who would not dance to its strings. Maybe the puppet had cut its own strings. Maybe some puppets don’t have any strings at all. For a moment, both the hand and the boy learned something about power and equality.</p><p>The boy shook his head before turning to walk away. The hand withdrew into the window slowly, bangles chiming one final time — as it disappeared into its world.</p><p>The boy kept walking. His stomach ached, but his back remained straight.</p><p>Like any living creature, the boy was drawn to his mother by hunger. She would provide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N30BbY1BwBMFqYmLvvR_bQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e575decbe1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Blue Dot]]></title>
            <link>https://karthickragavendran.medium.com/the-blue-dot-bf443bccd920?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf443bccd920</guid>
            <category><![CDATA[literacy]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[empowerment]]></category>
            <category><![CDATA[short-story]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Thu, 09 May 2024 16:54:01 GMT</pubDate>
            <atom:updated>2024-05-25T00:04:14.455Z</atom:updated>
            <content:encoded><![CDATA[<p>Selvi was fifty-eight when her husband passed away. She lived by herself in a rural village in southern Tamilnadu. She had the farm and cattle to look after.</p><p>With each passing day, she felt lonelier and lonelier.</p><p>The home was quiet. The farm was quiet. A few villagers talked. But those words did not count to her. The silence grew suffocating.</p><p>One day, Selvi learned about an evening school for adults in the nearby town. She would hear new voices she thought.</p><p>She enrolled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZmVPr6sG5XIyKEXpxRV0g.jpeg" /></figure><h4>The bus stop</h4><p>The day arrived. Her first day of school. She got ready and reached the bus stop early.</p><p>One problem. She did not know how to take a bus.</p><p>She had her husband all along.</p><p>She would carefully watch her husband squint at the approaching bus. It was always exciting for her when he said, ‘<em>ம்ம், இது போகும் ஏறு ஏறு. (Hmm, this is the one. Get on, get on.)’</em></p><p>She missed his presence by her side.</p><p>She felt alone at the crowded bus stop. People came and took their buses. Buses came and took its people.</p><p>She felt left out.</p><p>Too ashamed to ask for help, she decided to make the three-kilometer walk to the school on foot. It was 6 kilometers every day.</p><p>Selvi was the oldest in the class. The first time when she entered, She felt like everyone asking ‘<em>Why bother?</em>’. But no one bothered. They had their lives and concerns.</p><p>She did like the sound of people talking around her in the classroom. The teacher arrived on time and taught something by drawing on the blackboard.</p><p>She understood nothing.</p><h4>Malar</h4><p>Selvi had a friend named Malar, a single mother in her 30s with a young son. Malar worked as a construction worker during the day. Her reason for joining the evening school was quite unusual.</p><p>One night, like any other, her son refused to eat the food cooked with poverty. He cried his soul out.</p><p>She was too exhausted to convince him.</p><p>‘<em>சாப்புடு. வேற செய்ய முடியாது. அம்மா படிக்கல. படிச்சிருந்தா நல்ல வேலைக்கு போய் உனக்கு கறி சோறே போட்ருப்பேன். (Eat. I can’t do anything else. Mother doesn’t know how to read. If I had studied, I could have gotten a good job and served you proper meals.)</em>’ She expressed her inability.</p><p>‘<em>சரி எப்போ தான்</em> <em>படிப்ப??(Okay, when will you study??)’</em> The little son yelled, his face wet with tears and mucus.</p><p>It made her think, <em>why not?</em></p><p>Malar joined the evening school, dreaming of passing the eighth grade and becoming a worker who could do math and feed good food to her child.</p><h4>The red dot</h4><p>Whenever they had time in class, the two friends, Selvi and Malar, would chat.</p><p><strong>‘<em>பொட்டு வெச்சிக்க கூடாதோ? </em></strong><em>(You shouldn’t apply the kumkum dot on your forehead??</em><strong><em>)’</em></strong> Malar asked.</p><p>‘<em>ம்ம்? </em><strong><em>வெச்சிக்கலாம்.</em></strong><em> எனக்கு பிடிக்கும். ஆனா ஊர்ல வித்தியாசமா பாப்பாங்க. ஏதாச்சும் பேசுவாங்க. அதான் வெக்கிறது இல்ல. (Hmm? One can apply it. I like it. But in our village, people will see it differently. They’ll talk about it. That’s why I don’t apply it.)</em>’</p><p>‘<em>ஓ...(Oh…)</em>’ Malar understood.</p><h4>பார்வை</h4><p>One evening while walking towards the school, Selvi found it hard. She felt exhausted. About everything.</p><p>She stopped and sat on a small bridge wall, catching breaths.</p><p>Nothing was going well for her. She could not manage the farm properly. The school did not make sense one bit.</p><p>Her classmates progressed to pencil-and-paper, some even to pen-and-paper while she remained stuck with chalk and slate, still practicing writing letters.</p><p>After a few minutes, Selvi took out her slate, her eyes fixed upon it with frustration. She did not want to suffer anymore.</p><p>She quit.</p><p>Throwing the slate into the bushes, Selvi turned around and walked back towards her village.</p><p>A bus went past her.</p><p>She realized that she recognized a few letters on the nameplate.</p><p>Her heart skipped a beat.</p><p>She rushed back to the bus stop and waited anxiously for another bus with a nameplate. Within a few minutes, one appeared at the end of the road. She squinted her eyes.</p><p>The letters on the bus nameplate looked familiar.</p><p>The bus stopped for her. The bus conductor peeked out, seeing if she was coming.</p><p>She kept reading the nameplate intently.</p><p>‘<em>எங்க மா போகணும்? (Where do you need to go, ma’am?)</em>’ The bus conductor asked.</p><p>‘<em>ஒரு நிமிசம்! (One moment!)’</em>. She raised her finger, asking the conductor to wait. She focused on the board. Her eyes widened. She understood the destination name.</p><p>But buses to that destination had other routes as well. The nameplate had a “via” section under the main destination.</p><p>The driver started moving the bus. She stepped in front of it to read the full board. ‘<em>ஒரு நிமிசம்ய்யா… (One moment, brother…)</em>’</p><p>The “via” section had four names. It was easier since she knew the town names around her village. Her school stop name was the third. She knew where the bus was headed.</p><p>She could read.</p><p>‘<em>வண்டிய எடுங்க… வண்டிய எடுங்க… (Lets go!!)</em>’ She boarded with a proud smile on her face. The conductor and the driver were not happy.</p><p>She took the window seat. The breeze greeted her warmly.</p><p>Outside the window, shops flashed by. Each had a name board. But the bus was moving too fast for her to read them.</p><p>Still, she managed to decipher a few small ones — a bookshop named ‘தமிழ் (Thamizh)’ a fruit vendor called ‘சோலை (Solai)’.</p><p>And then, a tiny tea stall caught her eye. The board read ‘செல்வி (Selvi)’.</p><p>She giggled loudly.</p><p>The conductor stared at the troublesome lady. ‘<em>ஒன்னுமில்லைய்யா… (It’s nothing…)</em>’ she replied, giggling uncontrollably.</p><h4>One step at a time. Forward.</h4><p>She entered the classroom.</p><p>One problem. She had thrown her slate away.</p><p>Malar saw Selvi’s empty bag and tore some papers from her notebook to give to Selvi. A student offered an extra blue pen from their bag. No one had an extra pencil.</p><p>Selvi wrote her name at the top right corner of the paper.</p><p><strong>செலவி </strong>(Selavi)</p><p>Something didn’t seem right, she thought, squinting closely. Ah, it was the dot.</p><p><strong>செல்வி </strong>(Selvi)</p><p>There, she fixed it.</p><p>A blue dot that would never leave her forehead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf443bccd920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AuthN and AuthZ with TRPC]]></title>
            <link>https://karthickragavendran.medium.com/authn-and-authz-with-trpc-dc8021d05710?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc8021d05710</guid>
            <category><![CDATA[trpc]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 11:45:25 GMT</pubDate>
            <atom:updated>2024-01-30T11:45:25.512Z</atom:updated>
            <content:encoded><![CDATA[<p>This article dives into practical ways to secure your tRPC endpoints using middleware and private procedures within an Express environment. We’ll assume you’re familiar with the core concepts of authentication (AuthN) and authorization (AuthZ) and focus on the implementation details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-a9uTmaEtwAzHEPnWFNVA.png" /></figure><h4>Context</h4><p>Attach the authorization token into the context. This context will get called on all requests so lets keep it light.</p><pre>import { CreateExpressContextOptions } from &#39;@trpc/server/adapters/express&#39;<br><br>export const createTRPCContext = ({<br>  req,<br>  res,<br>}: CreateExpressContextOptions) =&gt; {<br>  const header = req.headers.authorization<br>  const token = header?.split(&#39; &#39;)[1]<br>  // Bearer eylkdflk<br>  return { req, res, token }<br>}</pre><h4>TRPC Instance</h4><p>The ‘t’ in the below code is the Trpc instance and it acts as a gateway to various tRPC functionalities, including defining routes, procedures, and utilizing middleware.</p><pre>import { initTRPC } from &#39;@trpc/server&#39;<br>import { createTRPCContext } from &#39;./context&#39;<br><br>export const t = initTRPC.context&lt;typeof createTRPCContext&gt;().create()</pre><p>Notice I included the context while creating this makes sure the context we access inside the procedure is typed with the token string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdVjBni7U3i4vKuePrGydw.png" /></figure><p>Now we can take the token and verify it inside the queries and mutations but lets use middleware for that.</p><h3>Middleware</h3><p>Lets create a isAuthed middleware. This is going to be used for both Authentication and Authorization of the requester.</p><h4>Requirements</h4><ul><li>Acts as a gatekeeper for procedures, enforcing authentication and authorization.</li><li>Verifies provided tokens and extracts user information.</li><li>Checks user roles against required roles for authorized access.</li><li>Adds uid to the context for use within procedures.</li></ul><h4>Design</h4><ul><li>Wraps procedures to apply isAuthed middleware, ensuring only authenticated and authorized users can access them.</li><li>Accepts optional roles argument to specify required roles for access.</li></ul><pre>export const privateProcedure = (...roles: Role[]) =&gt;<br>  t.procedure.use(isAuthed(...roles))</pre><h4>Usage</h4><p>The privateProcedure is versatile to be used for creating authenticated routes and role based routes.</p><p>Also remember the ctx now has uid.</p><pre>export const authRoutes = router({<br>  users: privateProcedure(&#39;admin&#39;).query(({ctx}) =&gt; {<br>    // Only admins can access this procedure.<br><br>    // Context also contains the uid.<br>    const { uid } = ctx<br><br>  }),<br>  user: privateProcedure().query(() =&gt; {<br>    // Only authenticated users can access this procedre.<br>  }),<br>})</pre><h4>Implementation</h4><ul><li>Checks for a valid token in the context.</li><li>Verifies the token using jsonwebtoken.</li><li>Extracts user ID and calls authorizeUser for role-based authorization.</li><li>Adds user ID to the context for subsequent use.</li></ul><pre>import { TRPCError } from &#39;@trpc/server&#39;<br>import { t } from &#39;./trpc&#39;<br>import { Role } from &#39;./types&#39;<br>import { JwtPayload, verify } from &#39;jsonwebtoken&#39;<br>import { authorizeUser } from &#39;./util&#39;<br><br>export const isAuthed = (...roles: Role[]) =&gt;<br>  t.middleware(async (opts) =&gt; {<br>    const { token } = opts.ctx<br>    if (!token) {<br>      throw new TRPCError({<br>        code: &#39;FORBIDDEN&#39;,<br>        message: &#39;Token not found.&#39;,<br>      })<br>    }<br>    console.log(&#39;token&#39;, token)<br>    let uid<br><br>    try {<br>      const user = await verify(token, process.env.NEXTAUTH_SECRET || &#39;&#39;)<br>      uid = (user as JwtPayload).uid<br>      console.log(&#39;uid&#39;, uid)<br>    } catch (error) {<br>      throw new TRPCError({<br>        code: &#39;FORBIDDEN&#39;,<br>        message: &#39;Invalid token.&#39;,<br>      })<br>    }<br><br>    await authorizeUser(uid, roles)<br><br>    return opts.next({ ...opts, ctx: { ...opts.ctx, uid } })<br>  })</pre><ul><li>authorizeUser: Compares user roles against required roles, throwing a TRPCError if access is not granted.</li><li>getUserRoles: Fetches user roles from the database based on user ID.</li></ul><pre>export const authorizeUser = async (<br>  uid: string,<br>  roles: Role[],<br>): Promise&lt;void&gt; =&gt; {<br>  if (!roles || roles.length === 0) {<br>    return // No specific roles required, access is granted<br>  }<br><br>  const userRoles = await getUserRoles(uid)<br><br>  if (!userRoles.some((role) =&gt; roles.includes(role))) {<br>    throw new TRPCError({<br>      code: &#39;FORBIDDEN&#39;,<br>      message: &#39;User does not have the required role(s).&#39;,<br>    })<br>  }<br>}<br><br>export const getUserRoles = async (uid: string): Promise&lt;Role[]&gt; =&gt; {<br>  const [adminExists, managerExists] = await Promise.all([<br>    prisma.admin.findUnique({ where: { uid } }),<br>    prisma.manager.findUnique({ where: { uid } }),<br>  ])<br><br>  const roles: Role[] = []<br>  if (adminExists) roles.push(&#39;admin&#39;)<br>  if (managerExists) roles.push(&#39;manager&#39;)<br><br>  return roles<br>}</pre><h3>Row level permission</h3><h4>Implementation</h4><ul><li>Enforces fine-grained access control at the data level.</li><li>Checks if the requesting user’s roles or ID match allowed roles or a list of allowed user IDs.</li><li>Throws a TRPCError if access is denied.</li></ul><pre><br>export const checkRowLevelPermission = async (<br>  uid: string,<br>  allowedUids: string | string[],<br>  allowedRoles: Role[] = [&#39;admin&#39;],<br>) =&gt; {<br>  const userRoles = await getUserRoles(uid)<br><br>  if (userRoles?.some((role) =&gt; allowedRoles.includes(role))) {<br>    return true<br>  }<br><br>  const uids =<br>    typeof allowedUids === &#39;string&#39;<br>      ? [allowedUids]<br>      : allowedUids.filter(Boolean)<br><br>  if (!uids.includes(uid)) {<br>    throw new TRPCError({<br>      code: &#39;FORBIDDEN&#39;,<br>      message: &#39;You are not allowed to do this action.&#39;,<br>    })<br>  }<br>}</pre><h4>Usage</h4><ul><li>Call checkRowLevelPermission before accessing sensitive data or performing actions to ensure authorized access.</li><li>Provide the requesting user’s ID, allowed user IDs, and optional allowed roles.</li></ul><pre>export const authRoutes = router({<br>  user: privateProcedure()<br>    .input(formSchemaUser)<br>    .query(async ({ ctx, input }) =&gt; {<br>      const user = await prisma.user.findUnique({ where: { uid: input.uid } })<br>      if (!user) {<br>        throw new TRPCError({ code: &#39;NOT_FOUND&#39; })<br>      }<br><br>      checkRowLevelPermission(ctx.uid, user.uid)<br>      // [] of uids as allowedUids. <br>      // checkRowLevelPermission(ctx.uid, [user.uid, ...managerUids])<br><br>      // Optional: [] of roles<br>      // checkRowLevelPermission(ctx.uid, [user.uid, ...managerUids]], [&#39;admin&#39;, &#39;manager&#39;])<br>      return user<br>    }),<br>})</pre><h4>Key Points</h4><ul><li>Middleware provides a flexible way to intercept and handle requests before reaching procedures.</li><li>Private procedures offer a convenient way to protect specific routes with authentication and authorization.</li><li>Utility functions like authorizeUser and getUserRoles help organize authorization logic.</li><li>Row level permissions enable granular control over data access within procedures.</li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc8021d05710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approaching Midnight.]]></title>
            <link>https://karthickragavendran.medium.com/approaching-midnight-9d2894042c13?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d2894042c13</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[addiction]]></category>
            <category><![CDATA[short-story]]></category>
            <category><![CDATA[focus]]></category>
            <category><![CDATA[fiction]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 19:24:26 GMT</pubDate>
            <atom:updated>2023-11-18T19:24:26.595Z</atom:updated>
            <content:encoded><![CDATA[<p>Time is a funny thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR97iGFIajkI5T6becJBrg.png" /></figure><h4>Child me</h4><p>Sitting on a boring Saturday morning, waiting for Sakthimaan. I glance at the clock — each second drags. Patiently waiting, scratching my head, but clapping at each tick.</p><p>‘Yay, only 14,400 more ticks to Sakthimaan! Totally doable!’</p><p>But then, a tick goes backward? 🥺</p><p>The clock reclaims that second. The innocent little man cheers again. Little do I know, Sakthimaan time will never come in this eternity.</p><h4>Adult me</h4><p>Okay, it’s Saturday morning. I open YouTube.</p><p>Suddenly, it’s 4 pm. ‘Did I fall into a video vortex?’ 😕</p><p>‘No. This is not good. This is not healthy! Let me watch a YouTube video on how to stop YouTube addiction.’</p><p>I glance up — it’s 2 am. ‘Wait, what? How?’ 🥺</p><p>I get up from the computer. Stretch my hands. ‘Time for bed.🥱’</p><p>Birds chirping outside. It is 6 am.</p><p>‘Welcome to Sunday! A day for sleep.’ I go to sleep.</p><p>Wake up. It’s Sunday night. Weekend, poof, gone.</p><p>‘Tomorrow’s office,’ I think. ‘Just one video to ease the pain.😕’ I start the video.</p><p>The video plays. Time has no patience. It’s 8 am. The alarm blares.</p><p>‘Monday??? Wow!!!’</p><p>I sit in the office. Turn on the computer. Night falls. The manager shows up.</p><p>‘You know you don’t have to work late nights, especially on Fridays?’ he says.</p><p>‘It’s Friday??’</p><p>‘It is. And it’s not appraisal time. So leave!’ The manager gives a smile into my soul.</p><p>I come home. I need to buy some socks. Open the Amazon app. Time check — Sunday evening.</p><p>‘Nope 😑! Time to snap out of this!’ I decide. ‘Some meditation to clear my head.’</p><p>I sigh. The computer sleeps, I lean back, taking deep breaths, eyes on the clock, trying to stop it.</p><p>The minute hand slows down.</p><p>The second hand slows down.</p><p>Both stop.</p><p>‘I won?’</p><p>Nope.</p><p>The hour hand is ticking.</p><p>6… 7… 8… My evening is gone.</p><p>12pm… 8am…<br>THE ALARM SCREAMS!!!</p><p>‘Why???😨’</p><p>I go to bathe. Come out. It’s dark again. Is it Friday? I check the date. Of course. It is.</p><p>I sit at the computer. Look at the date on the monitor.</p><p>It’s Friday, 30th December. “It is December. Oh,” I realize.</p><p>30th. It says.</p><p>It ticks to 31st.</p><p>31st it says now.</p><p>1st…<br>2nd…<br>3rd…<br>3rd…<br>3rd…<br>3rd of April…<br>3rd of May…<br>3rd of June…<br>3rd of July…<br>3rd of July…<br>3rd of July…<br>3rd of July…<br>3rd of July 2026…<br>3rd of July 2027…<br>3rd of July 2028…<br>3rd of July 2029…</p><p>I freeze, hands trembling off the mouse. I shut down the computer. Sit staring at the turned-off computer.</p><p>Time does not stop when I do not look. It does its job.</p><p>It is calm for a while. I close my eyes. I hear kids’ sounds in the home. ‘I am a bachelor,’ I remind myself.</p><p>‘Thatha has shut down the computer! Thatha has shut down the computer!’ Kids flood into my room.</p><p>‘Finally!!!’ a 10-year-old sighs loudly.</p><p>‘Thatha always watching Tamanna songs…’ a little girl complains.</p><p>‘Get up, Thatha… Everyone is waiting for you in the family room,’ another grown one rushes.</p><p>‘Is Tamanna still alive?’ I ask, getting up with the help of my grandkids.</p><p>‘Yes, Thatha,’ one replies, pouring honey into the poor soul.</p><p>‘Who is Tamanna?’ the little one has no idea.</p><p>‘Some 80-year-old actress,’ one answers.</p><p>‘Why is he worried about an 82-year-old woman?’ one child pokes.</p><p>‘Because he is 85 years old, just like her,’ another replies.</p><p>‘Still, it is inappropriate for a 90-year-old to talk like this,’ another little thing judges me.</p><p>There’s a cake in the family room with the number 100.</p><p>I turn 100 by the time I reach the cake.</p><p>Happy birthday… Everyone sings.</p><p>I get a gift for cutting the cake. It’s a watch. It has one hand. It has 8 seconds to midnight.</p><p>‘What is this?’ I ask.</p><p>‘This watch shows life,’ someone answers.</p><p>‘Alright.’ I say.</p><p>5 seconds to midnight.<br>4…<br>3…<br>2…<br>1… a deep breath, the world stands in silence.</p><p>‘Good night,’ I whisper to everyone, and to no one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d2894042c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AuthN and AuthZ in NestJS using guards and decorators.]]></title>
            <link>https://karthickragavendran.medium.com/authn-and-authz-in-nestjs-using-guards-and-decorators-0c6c08c2a4a2?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c6c08c2a4a2</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 14:03:30 GMT</pubDate>
            <atom:updated>2023-11-18T14:03:30.473Z</atom:updated>
            <content:encoded><![CDATA[<h4>Guards in NestJS are responsible for determining whether a given request should be handled by the route handler or not. They are typically used for authentication and authorization purposes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LD9E9EgSRu_9Dy9O6NACcQ.jpeg" /></figure><h4>A Simple Auth Guard</h4><pre>import { Injectable, CanActivate, ExecutionContext } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class BasicAuthGuard implements CanActivate {<br>  canActivate(context: ExecutionContext): boolean {<br>    const request = context.switchToHttp().getRequest();<br>    // Simple authentication logic goes here<br>    return true; // or false based on the logic<br>  }<br>}</pre><h4>Imports</h4><ul><li>Injectable: Marks the class as a provider that can be managed by NestJS&#39;s dependency injection.</li><li>CanActivate: An interface that a guard class implements.</li><li>ExecutionContext: Provides details about the current request cycle.</li></ul><h4>The Guard Class:</h4><ul><li>BasicAuthGuard: The name of our custom guard class.</li></ul><h4>Dependency Injection:</h4><ul><li>The @Injectable() decorator allows NestJS to manage this class as a provider, enabling dependency injection if needed.</li></ul><h4>Implementing CanActivate</h4><ul><li>canActivate: This method is where the logic for guarding a route is implemented. It must return a boolean value.</li><li>The method receives an ExecutionContext instance, which provides details about the current request, response, and other contextual data.</li></ul><h4>Request Handling</h4><ul><li>context.switchToHttp().getRequest(): This extracts the request object from the current execution context. It&#39;s useful for accessing request details like headers, query parameters, or body.</li></ul><h4>Authentication Logic</h4><ul><li>Inside canActivate, you would implement your authentication logic. This could be as simple as checking a header or a token.</li><li>The return value (true or false) determines whether the request is allowed to proceed. true lets the request continue to the route handler, while false denies access.</li></ul><h4>Using the Guard</h4><ul><li>Apply the guard to routes using the @UseGuards decorator at the controller or route handler level.</li></ul><h3>Decorators</h3><p>Before looking at our detailed AuthGuard, let&#39;s see how we will use that and hence understand what to implement inside the guard.</p><pre>import { applyDecorators, SetMetadata, UseGuards } from &#39;@nestjs/common&#39;<br>import { AuthGuard } from &#39;src/common/auth/auth.guard&#39;<br><br>import { Role } from &#39;@foundation/util/types&#39;<br><br>export const AllowAuthenticated = (...roles: Role[]) =&gt;<br>  applyDecorators(SetMetadata(&#39;roles&#39;, roles), UseGuards(AuthGuard))<br><br>export const AllowAuthenticatedOptional = (...roles: Role[]) =&gt;<br>  applyDecorators(<br>    SetMetadata(&#39;allowUnauthenticated&#39;, true),<br>    SetMetadata(&#39;roles&#39;, roles),<br>    UseGuards(AuthGuard),<br>  )</pre><p>The AllowAuthenticated decorator checks if the request is authenticated and also restricts access to certain roles. It throws an error back if the request is not authenticated.</p><ul><li>applyDecorators: A NestJS function that combines multiple decorators into a single one.</li><li>SetMetadata: Used to define custom metadata. Here, it’s setting a ‘roles’ metadata with the roles passed as arguments.</li><li>UseGuards: It activates the specified guards, in this case, AuthGuard.</li><li>Usage: When applied, AllowAuthenticated ensures that only users with specified roles can access the route. The AuthGuard reads the &#39;roles&#39; metadata and checks if the authenticated user has one of these roles.</li></ul><p>AllowAuthenticatedOptional Decorator is similar to AllowAuthenticated, but with a key difference is the SetMetadata.</p><ul><li>SetMetadata(‘allowUnauthenticated’, true) sets additional metadata that tells AuthGuard to allow unauthenticated access to the route. It&#39;s useful for routes which reacts to unauthenticated users differently than throwing an error.</li></ul><h4>Authguard requirements</h4><ul><li>Check for an <strong>INTERNAL_SECRET</strong> and bypass the check. This can be used by trusted internal parties where generating a JWT may not be possible.</li><li><strong>AuthN</strong>: Get the BEARER eyblabla from the header and verify. Attach the information from token to the request as req.user. Get the metadata allowUnauthenticated to stop throwing unauthenticated error.</li><li><strong>AuthZ</strong>: Get the roles metadata and check the database for the roles.</li></ul><pre>import {<br>  CanActivate,<br>  ExecutionContext,<br>  ForbiddenException,<br>  Injectable,<br>  UnauthorizedException,<br>} from &#39;@nestjs/common&#39;<br>import { Reflector } from &#39;@nestjs/core&#39;<br>import { GqlExecutionContext } from &#39;@nestjs/graphql&#39;<br>import { JwtService } from &#39;@nestjs/jwt&#39;<br>import { PrismaService } from &#39;../prisma/prisma.service&#39;<br>import { Role } from &#39;@foundation/util/types&#39;<br><br>@Injectable()<br>export class AuthGuard implements CanActivate {<br>  constructor(<br>    private readonly reflector: Reflector,<br>    private jwtService: JwtService,<br>    private prisma: PrismaService,<br>  ) {}<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    const ctx = GqlExecutionContext.create(context)<br>    const req = ctx.getContext().req<br><br>    if (this.bypassWithApiSecret(req)) {<br>      //  The auth check bypassed.<br>      return true<br>    }<br><br>    await this.authenticateUser(req, context)<br><br>    return this.authorizeUser(context, req.user) // Check roles<br>  }<br><br>  private bypassWithApiSecret(req: any) {<br>    const apiSecret = req.headers[&#39;X-API-Secret&#39;]<br>    if (!apiSecret) {<br>      return false<br>    }<br>    if (apiSecret === process.env.INTERNAL_API_SECRET) {<br>      return true<br>    } else {<br>      throw new ForbiddenException(&#39;Nope.&#39;)<br>    }<br>  }<br><br>  private async authenticateUser(<br>    req: any,<br>    context: ExecutionContext,<br>  ): Promise&lt;void&gt; {<br>    const bearerHeader = req.headers.authorization<br>    const token = bearerHeader?.split(&#39; &#39;)[1]<br><br>    if (!token) {<br>      throw new UnauthorizedException(&#39;No token provided.&#39;)<br>    }<br><br>    try {<br>      const user = await this.jwtService.verify(token, {<br>        secret: process.env.NEXTAUTH_SECRET,<br>      })<br>      req.user = user<br>    } catch (err) {<br>      console.error(&#39;Token validation error:&#39;, err)<br>    }<br><br>    const allowUnauthenticated = this.getMetadata&lt;boolean&gt;(<br>      &#39;allowUnauthenticated&#39;,<br>      context,<br>    )<br><br>    if (!req.user &amp;&amp; !allowUnauthenticated) {<br>      throw new UnauthorizedException()<br>    }<br>  }<br><br>  private async authorizeUser(<br>    context: ExecutionContext,<br>    user: any,<br>  ): Promise&lt;boolean&gt; {<br>    const requiredRoles = this.getMetadata&lt;Role[]&gt;(&#39;roles&#39;, context)<br><br>    if (!requiredRoles || requiredRoles.length === 0) {<br>      return true // No specific roles required, access is granted<br>    }<br><br>    const roleCheckPromises = requiredRoles.map((role) =&gt;<br>      this.userHasRequiredRole(user.uid, role),<br>    )<br><br>    const roleCheckResults = await Promise.all(roleCheckPromises)<br>    return roleCheckResults.some(Boolean) // Return true if at least one role matches<br>  }<br><br>  // Helper methods<br><br>  private async userHasRequiredRole(<br>    uid: string,<br>    requiredRole: Role,<br>  ): Promise&lt;boolean&gt; {<br>    let userExists<br><br>    switch (requiredRole) {<br>      case &#39;admin&#39;:<br>        userExists = await this.prisma.admin.findUnique({<br>          where: { uid },<br>        })<br>        break<br>      case &#39;manager&#39;:<br>        userExists = await this.prisma.manager.findUnique({<br>          where: { uid },<br>        })<br>        break<br>    }<br><br>    return Boolean(userExists)<br>  }<br><br>  private getMetadata&lt;T&gt;(key: string, context: ExecutionContext): T {<br>    return this.reflector.getAllAndOverride&lt;T&gt;(key, [<br>      context.getHandler(),<br>      context.getClass(),<br>    ])<br>  }<br>}</pre><h4>1. canActivate Method</h4><ul><li>Purpose: It’s the heart of the guard, determining whether the current request should proceed.</li><li>Process: It creates a GqlExecutionContext from the standard ExecutionContext to support both REST and GraphQL contexts. Then it checks for an API secret to potentially bypass further checks. If bypassing is not applicable, it authenticates the user (authenticateUser) and checks their authorization (authorizeUser).</li></ul><h4>2. bypassWithApiSecret Method</h4><ul><li>Purpose: Offers an alternative path for internal or trusted services, bypassing standard authentication.</li><li>Process: It checks the request headers for a specific API secret. If the secret matches the environment variable, access is granted. If the secret is present but incorrect, it throws a ForbiddenException.</li></ul><h4>3. authenticateUser Method</h4><ul><li>Purpose: To validate the user’s identity using a JWT token.</li><li>Process: It extracts the token from the request’s authorization header. If a token is present, it’s verified using JwtService. A valid token results in attaching the user information to the request (req.user). If authentication is optional (allowUnauthenticated), it allows proceeding without a valid user.</li></ul><h4>4. authorizeUser Method</h4><ul><li>Purpose: To ensure the authenticated user has the necessary roles for the requested route.</li><li>Process: It retrieves the required roles using getMetadata. If roles are specified, it checks whether the user has any of the required roles (userHasRequiredRole). Access is granted if the user possesses at least one of the necessary roles.</li></ul><h4>5. userHasRequiredRole Helper Method</h4><ul><li>Purpose: To verify if the authenticated user has a specific role.</li><li>Process: Based on the role requirement (like ‘admin’ or ‘teacher’), it queries the database (using Prisma) to confirm if the user exists in the respective role table. You can have your own logic here. The roles may be stored in a Roles table.</li></ul><h4>6. getMetadata Helper Method</h4><ul><li>Function: A generic method to fetch custom metadata set on route handlers or controller classes.</li><li>Use: It simplifies metadata retrieval, making the guard more adaptable and easier to maintain.</li></ul><h4>GetUser Parameter Decorator</h4><p>We attached the user to the request (req.user). Let’s create a custom parameter decorator in NestJS that extracts the authenticated user’s details from a request, making them easily accessible within any controller or resolver method that utilizes this decorator.</p><pre>export const GetUser = createParamDecorator(<br>  (data: unknown, ctx: ExecutionContext) =&gt; {<br>    const context = GqlExecutionContext.create(ctx)<br>    const user = context.getContext().req.user<br>    return user<br>  },<br>)</pre><h4>Usage</h4><ol><li>Authenticated users only.</li></ol><pre>@AllowAuthenticated()<br>@Query(() =&gt; [PremiumNews])<br>async premiumNews() {<br>  return this.prisma.premiumNews.findMany()<br>}</pre><p>2. Authenticated with roles. The authenticated users with roles admin or manager can access.</p><pre>@AllowAuthenticated(&#39;admin&#39;, &#39;manager&#39;)<br>@Query(() =&gt; [User])<br>async users() {<br> return this.prisma.user.findMany()<br>}</pre><p>3. Get data relevant to the requester. Let&#39;s say we have studentMe query. And we don&#39;t want to rely on the inputstudentId sent by the requester.</p><pre>  @AllowAuthenticated()<br>  @Query(() =&gt; Student, { name: &#39;studentMe&#39; })<br>  async studentMe(@GetUser() user: GetUserType) {<br>    return this.prisma.student.findUnique({<br>      where: { uid: user.uid },<br>    })<br>  }</pre><p>4. AllowAuthenticatedOptional: Same as the above example but the query returns null instead of throwing an error.</p><pre>@AllowAuthenticatedOptional()<br>@Query(() =&gt; Student, { name: &#39;studentMe&#39; })<br>async studentMe(@GetUser() user: GetUserType) {<br>  if(!user?.uid){<br>    return null<br>  }<br>  return this.prisma.student.findUnique({<br>    where: { uid: user.uid },<br>  })<br>}</pre><p>Remember, we need to decorate the query with @AllowAuthenticated before using the @Getuser parameter decorator.</p><h3>Summary of Guard’s Workflow</h3><ul><li>Access Check: First, it checks for an API secret that can bypass other checks.</li><li>Authentication: Next, it verifies the user’s identity using a JWT.</li><li>Authorization: Then, it checks if the authenticated user has the required roles.</li><li>Decision: Finally, based on these checks, it decides whether to grant or deny access to the requested route.</li></ul><p>This AuthGuard will be a comprehensive and helpful solution for managing both authentication and authorization in your NestJS application. It&#39;s designed to be flexible, catering to various authentication scenarios while ensuring that access control remains robust and secure.</p><p>This is the AuthN and AuthZ setup of my <a href="https://github.com/karthickthankyou/foundationX">FoundationX</a> full-stack monorepo boilerplate.</p><p>For more cool stuff have a look at my <a href="https://github.com/karthickthankyou">Github</a>.</p><p>Happy coding 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c6c08c2a4a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Guide for NextAuth with Google and Credentials Providers in Next.js 13]]></title>
            <link>https://karthickragavendran.medium.com/setup-guide-for-nextauth-with-google-and-credentials-providers-in-next-js-13-8f5f13414c1e?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f5f13414c1e</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 06:51:48 GMT</pubDate>
            <atom:updated>2023-11-18T06:51:48.640Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide provides concise steps to integrate NextAuth in a Next.js 13 (app directory) application, using Google and Credentials Providers for authentication. The goal is to enable both Google sign-in and traditional email/password authentication in your Next.js project. Let&#39;s dive into the setup process, focusing on practical implementation and code examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIgkakfwCJd-lW2qYFGhOQ.png" /></figure><h3>Prerequisites</h3><p>Before starting, ensure you have the following:</p><ul><li>A Next.js 13 project setup with App directory enabled.</li><li>A Google Cloud account for obtaining OAuth credentials.</li></ul><p>To get your Google OAuth credentials:</p><ol><li>Go to the Google Cloud Console.</li><li>Create a new project or select an existing one.</li><li>Navigate to ‘APIs &amp; Services’ &gt; ‘Credentials’.</li><li>Click on ‘Create Credentials’ and select ‘OAuth client ID’.</li><li>Set up the consent screen, and choose ‘Web application’ as the application type.</li><li>Add your application’s URI to ‘Authorized redirect URIs’, typically http://localhost:3000/api/auth/callback/google for local development.</li><li>Once created, you’ll get your Client ID and Client Secret.</li></ol><h3>Installing NextAuth</h3><p>First, install NextAuth in your Next.js project:</p><pre>npm install next-auth</pre><p>Next, configure the basic structure in your authOptions file, using the code provided:</p><pre>import NextAuth from &#39;next-auth&#39;<br>import GoogleProvider from &#39;next-auth/providers/google&#39;<br>import CredentialsProvider from &#39;next-auth/providers/credentials&#39;</pre><pre>export const authOptions = {<br>  // Providers array will be configured in the next steps<br>  providers: [],<br>  session: {<br>    strategy: &#39;jwt&#39;<br>  },<br>  // Additional configuration will be added here<br>}</pre><pre>export const getAuth = () =&gt; getServerSession(authOptions)</pre><p>This sets up NextAuth with an empty array for providers, which we’ll fill in the following sections, and specifies JWT for session management. The getAuth function is for server-side session retrieval.</p><h3>Configuring Google Provider</h3><p>To integrate Google authentication, update the providers array in authOptions:</p><pre>import GoogleProvider from &#39;next-auth/providers/google&#39;</pre><pre>// ... other imports</pre><pre>export const authOptions = {<br>  providers: [<br>    GoogleProvider({<br>      clientId: process.env.GOOGLE_CLIENT_ID,<br>      clientSecret: process.env.GOOGLE_CLIENT_SECRET,<br>    }),<br>    // ... other providers<br>  ],<br>  // ... other configurations<br>}</pre><p>In this setup:</p><ul><li>clientId and clientSecret are the OAuth credentials obtained from Google Cloud Console.</li><li>Store these credentials in environment variables (GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET) for security.</li></ul><h3>5. Setting Up Credentials Provider</h3><p>For email/password authentication, add the Credentials Provider:</p><pre>import CredentialsProvider from &#39;next-auth/providers/credentials&#39;<br>import bcrypt from &#39;bcrypt&#39;</pre><pre>// ... other imports</pre><pre>export const authOptions = {<br>  providers: [<br>    // ... GoogleProvider configuration<br>    CredentialsProvider({<br>      name: &#39;Credentials&#39;,<br>      credentials: {<br>        email: { label: &#39;Email&#39;, type: &#39;email&#39; },<br>        password: { label: &#39;Password&#39;, type: &#39;password&#39; },<br>      },<br>      async authorize(credentials) {<br>        // Add logic to verify credentials here<br>        if (!credentials) return null<br>        const { email, password } = credentials<br>        // Fetch user and password hash from your database<br>        // Example: const user = await getUserByEmail(email)<br>        if (user &amp;&amp; bcrypt.compareSync(password, user.passwordHash)) {<br>          return { id: user.id, name: user.name, email: user.email }<br>        } else {<br>          throw new Error(&#39;Invalid credentials&#39;)<br>        }<br>      },<br>    }),<br>  ],<br>  // ... other configurations<br>}</pre><p>Key points:</p><ul><li>Define credentials with email and password fields.</li><li>Implement the authorize function to verify user credentials.</li><li>Fetch the user’s hashed password from your database.</li><li>Use bcrypt to compare the provided password with the stored hash.</li><li>If valid, return the user object; otherwise, throw an error.</li></ul><p>This configuration enables users to log in with their email and password, while Google Provider allows for Google account sign-ins. The next sections will cover integrating these into your Next.js application routes and managing user sessions.</p><h3>Detailed Breakdown of authOptions in NextAuth</h3><p>Lets have a closer look at theauthOptions structure and its components:</p><pre>export const authOptions: NextAuthOptions = {<br>  providers: [<br>    // GoogleProvider and CredentialsProvider configurations<br>  ],<br>  session: {<br>    strategy: &#39;jwt&#39;,<br>    maxAge: 1 * 24 * 60 * 60, // 1 day<br>  },<br>  jwt: {<br>    // JWT encoding and decoding configurations<br>  },<br>  callbacks: {<br>    // signIn, session callbacks<br>  },<br>  pages: {<br>    signIn: &#39;/signIn&#39;, // Custom sign-in page<br>  },<br>}</pre><p>In this setup:</p><ul><li>providers array includes Google and Credentials Providers.</li><li>session configures JWT session management.</li><li>jwt handles encoding and decoding of JWT tokens.</li><li>callbacks allow custom handling of signIn and session events.</li><li>pages lets you specify custom pages for sign-in.</li></ul><h3>Authentication Routes</h3><p>Next, set up the authentication routes in your Next.js application. This involves creating API routes that handle authentication requests:</p><pre>// src/app/api/auth/[...nextauth]/route.ts</pre><pre>import { authOptions } from &#39;@foundation/common/src/authOptions&#39;<br>import NextAuth from &#39;next-auth&#39;</pre><pre>const handler = NextAuth(authOptions)</pre><pre>export { handler as GET, handler as POST }</pre><p>In this code:</p><ul><li>Import NextAuth and authOptions.</li><li>Create a handler with NextAuth(authOptions).</li><li>Export the handler as the default export for handling GET and POST requests on /api/auth/*.</li></ul><p>These routes work with our authOptions configuration to handle user authentication. When a user attempts to sign in or interact with the authentication system, these API routes process the requests according to our configuration.</p><p>We can have a route to get back the token generated for the authenticated users.</p><pre>// src/app/api/auth/token/route.ts<br><br>import { NextRequest, NextResponse } from &#39;next/server&#39;<br>import { cookies } from &#39;next/headers&#39;<br><br>export async function GET(req: NextRequest, res: NextResponse) {<br>  const getCookies = cookies()<br>  const nextAuthSession = getCookies.get(&#39;next-auth.session-token&#39;)?.value || &#39;&#39;<br><br>  return NextResponse.json(nextAuthSession)<br>}</pre><h3>The Flow</h3><p>It begins with the user’s choice between Google or email/password authentication. For Google authentication, the user is redirected to Google and back, while for email/password, the credentials are verified through the authorize function. This process ensures that only valid credentials grant access, and upon successful authentication, the user&#39;s session is created and managed for subsequent application use.</p><pre>|<br>|-- User Initiates Authentication<br>|   |-- Via Google Provider<br>|   |   `-- Redirect to Google -&gt; User Authenticates -&gt; Redirect back to Application<br>|   |<br>|   `-- Via Credentials Provider<br>|       `-- User Enters Email and Password<br>|           `-- authorize Function<br>|               |-- If Valid: User Authenticated<br>|               `-- If Invalid: Error Returned<br>|<br>|-- Post-Authentication<br>|   `-- signIn Callback Triggered<br>|<br>|-- Session Creation and Management<br>|   `-- session Callback Updates Session Information<br>|<br>`-- User Access<br>    `-- User Fully Authenticated and Accesses Application</pre><h3>UI components</h3><p>The SignIn component is a key interface element where users interact with the authentication system. It uses form management to handle user inputs for email and password, and provides an option to sign in with Google.</p><pre>// signIn.tsx<br>export const SignIn = () =&gt; {<br>  const { register, handleSubmit } = useFormSignin()<br><br>  return (<br>    &lt;AuthLayout title=&quot;Login&quot;&gt;<br>      &lt;form onSubmit={handleSubmit(({ email, password }) =&gt; signIn(&#39;credentials&#39;, { email, password }))}&gt;<br>        &lt;Label title=&quot;Email&quot;&gt;<br>          &lt;Input {...register(&#39;email&#39;)} placeholder=&quot;Email&quot; /&gt;<br>        &lt;/Label&gt;<br>        &lt;Label title=&quot;Password&quot;&gt;<br>          &lt;Input {...register(&#39;password&#39;)} type=&quot;password&quot; placeholder=&quot;Password&quot; /&gt;<br>        &lt;/Label&gt;<br>        &lt;Button type=&quot;submit&quot;&gt;Submit&lt;/Button&gt;<br>      &lt;/form&gt;<br><br>      &lt;Link href=&quot;/register&quot;&gt;Register&lt;/Link&gt;<br>      <br>      &lt;button onClick={() =&gt; signIn(&#39;google&#39;)}&gt;Sign in with Google&lt;/button&gt;<br>    &lt;/AuthLayout&gt;<br>  )<br>}</pre><pre><br>// register.tsx<br><br>export const Register = () =&gt; {<br>  const { register, handleSubmit } = useFormRegister()<br><br>  return (<br>    &lt;AuthLayout title=&quot;Register&quot;&gt;<br>      &lt;form<br>        onSubmit={handleSubmit(async ({ email, password, name }) =&gt; {<br>          // Backend registration call<br>          const user = await fetchGraphQL({<br>            document: CreateUserWithCredentialsDocument,<br>            variables: { email, password, name },<br>          })<br><br>          // Handle registration response<br>          if (user.error) {<br>            toast({ title: user.error })<br>          } else if (user.data) {<br>            toast({ title: `User created. 🎉` })<br>            signIn(&#39;credentials&#39;, { email, password, callbackUrl: &#39;/&#39; })<br>          }<br>        })}<br>      &gt;<br>        &lt;Input {...register(&#39;email&#39;)} placeholder=&quot;Email&quot; /&gt;<br>        &lt;Input {...register(&#39;password&#39;)} type=&quot;password&quot; placeholder=&quot;••••••&quot; /&gt;<br>        &lt;Input {...register(&#39;name&#39;)} placeholder=&quot;Name&quot; /&gt;<br>        &lt;Button type=&quot;submit&quot;&gt;Submit&lt;/Button&gt;<br>      &lt;/form&gt;<br>      <br>      &lt;Link href=&quot;/signIn&quot;&gt;Already have an account? Sign in&lt;/Link&gt;<br>      &lt;button onClick={() =&gt; signIn(&#39;google&#39;)}&gt;Sign in with Google&lt;/button&gt;<br>    &lt;/AuthLayout&gt;<br>  )<br>}</pre><p>On the registration page, we do the following,</p><ul><li>User inputs for email, password, and name.</li><li>Submission handling that interacts with <strong>our own backend</strong> for registration.</li><li>Feedback for success or error during the registration process.</li><li>Links and options for alternative sign-in methods.</li></ul><h3>Understanding the Scope of This Guide</h3><p>Before we dive into the details of setting up authentication in Next.js using NextAuth, it’s important to note that this guide focuses specifically on the front-end configuration of authentication mechanisms. Key components not covered in this guide include:</p><ul><li>Database Schema: The backend setup for storing user credentials, especially for the Credentials Provider, is not covered. A complete implementation requires a database to store encrypted passwords and user details.</li><li>Backend Registration Routes: The guide does not include backend routes necessary for user registration and management, which are critical for a fully functional authentication system.</li><li>Complete Backend Integration: While we discuss the front-end aspects of authentication, integrating these with a backend service is beyond the scope of this article.</li></ul><p>This guide is part of a larger setup and is intended to provide a starting point for integrating authentication in a Next.js application. For a comprehensive implementation, additional backend development and database setup are required.</p><blockquote>You can see the full working implementation in this mono repo repository. <a href="https://github.com/karthickthankyou/foundationX">https://github.com/karthickthankyou/foundationX</a></blockquote><p>Link for repository: <a href="https://github.com/karthickthankyou/foundationX">https://github.com/karthickthankyou/foundationX</a></p><p>Thank you for reading. I appreciate your time and interest in my work. For more full-fledged open-source products, You can follow me on <a href="https://github.com/karthickthankyou">Github</a> or <a href="https://www.linkedin.com/in/iamkarthickr/">LinkedIn</a>.</p><p>Happy coding. 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f5f13414c1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS + Prisma + Typescript = Robust, and Powerful GraphQL APIs in less than a day.]]></title>
            <link>https://karthickragavendran.medium.com/nestjs-prisma-typescript-robust-and-powerful-graphql-apis-in-less-than-a-day-d55cf6e6e987?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55cf6e6e987</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 07:25:57 GMT</pubDate>
            <atom:updated>2023-08-14T07:33:48.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63fY3QFBtv6-DeAUbEJ7kA.jpeg" /></figure><p>Code: <a href="https://github.com/karthickthankyou/nestjs-prisma-simple-graphql-api">https://github.com/karthickthankyou/nestjs-prisma-simple-graphql-api</a></p><h4>Getting started</h4><pre>// Initialize a new nest application<br>npx nest new graphql-api --package-manager=yarn<br><br>// Install dependencies<br>yarn add graphql @apollo/server @nestjs/graphql @nestjs/apollo</pre><p>Add Graphql module in Nestjs</p><pre>GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({   // Configuring the GraphQL module using the Apollo driver with a specific configuration type<br>      driver: ApolloDriver,                    // Specifying the Apollo driver to be used for GraphQL<br>      fieldResolverEnhancers: [&#39;guards&#39;],      // Applying guards as field resolver enhancers, providing additional control and security<br>      autoSchemaFile: join(process.cwd(), &#39;src/schema.gql&#39;), // Automatically generating the schema file from types and resolvers, saving it in the specified path<br>      introspection: true,                     // Enabling introspection, allowing tools like GraphQL Playground to fetch the schema<br>}),</pre><p>Using the Apollo driver, this configuration provides a solid foundation for a GraphQL server in NestJS. It includes automatic schema generation, field-level security through guards, and introspection for development tooling.</p><h4>Setup env Config</h4><pre>yarn add @nestjs/config<br><br>ConfigModule.forRoot(),</pre><p>The @Module decorator for the AppModule looks like the one below.</p><pre>@Module({<br>  imports: [<br>    ConfigModule.forRoot(),<br>    GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({<br>      driver: ApolloDriver,<br>      fieldResolverEnhancers: [&#39;guards&#39;],<br>      autoSchemaFile: join(process.cwd(), &#39;src/schema.gql&#39;),<br>      introspection: true,<br>    }),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule implements NestModule {}</pre><h4>Enable nest-cli plugin</h4><p>The plugin simplifies the development process when working with GraphQL in NestJS, providing automation and addressing some of TypeScript’s limitations. It aids in structuring the code efficiently, making it easier to define and maintain GraphQL schemas.</p><pre>  &quot;$schema&quot;: &quot;https://json.schemastore.org/nest-cli&quot;,<br>  &quot;collection&quot;: &quot;@nestjs/schematics&quot;,<br>  &quot;sourceRoot&quot;: &quot;src&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;deleteOutDir&quot;: true,<br>    &quot;plugins&quot;: [{ &quot;name&quot;: &quot;@nestjs/graphql&quot; }] // Add this.<br>  }<br>}</pre><p>Read more about this <a href="https://docs.nestjs.com/graphql/cli-plugin">here</a>.</p><h4>The test database</h4><p>Let&#39;s have a Postgres database running locally using docker.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  db:<br>    container_name: autospace_db<br>    image: postgres<br>    restart: always<br>    ports:<br>      - 1000:5432<br>    environment:<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_DB: ${POSTGRES_DB}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>    volumes:<br>      - db_data:/var/lib/postgresql/data<br>  pgadmin:<br>    container_name: autospace_pgadmin<br>    image: dpage/pgadmin4<br>    restart: always<br>    environment:<br>      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_EMAIL}<br>      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_PASSWORD}<br>    ports:<br>      - &#39;1100:80&#39;<br>    depends_on:<br>      - db<br>volumes:<br>  db_data:</pre><p>Add the environment variables POSTGRES_USER, POSTGRES_DB, POSTGRES_PASSWORD, PGADMIN_EMAIL, and PGADMIN_PASSWORD in a .env in the same location as the docker-compose.yml file.</p><p>Make sure you have the docker desktop installed and running. Run the database using the below command.</p><pre>docker compose up -d</pre><h4>Initialize Prisma</h4><pre>yarn add prisma -D<br><br>yarn prisma init</pre><p>Modify the DATABASE_URL in the .env file.</p><h4>Design Prisma Schema</h4><pre>generator client {<br>    provider = &quot;prisma-client-js&quot;<br>}<br><br>datasource db {<br>    provider = &quot;postgresql&quot;<br>    url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>model User {<br>    uid       String   @id<br>    createdAt DateTime @default(now())<br>    name      String? // Nullable field<br><br>    posts    Post[] // One-to-many relation with Post<br>    comments Comment[] // One-to-many relation with Comment<br>}<br><br>model Post {<br>    id        Int     @id @default(autoincrement())<br>    title     String<br>    body      String<br>    published Boolean @default(false) // With default value<br><br>    author   User      @relation(fields: [authorId], references: [uid]) // Many-to-one relation with User<br>    authorId String<br>    comments Comment[] // One-to-many relation with Comment<br>}<br><br>model Comment {<br>    id     Int    @id @default(autoincrement())<br>    text   String<br>    post   Post   @relation(fields: [postId], references: [id]) // Many-to-one relation with Post<br>    postId Int<br>    user   User   @relation(fields: [userId], references: [uid]) // Many-to-one relation with User<br>    userId String<br>}</pre><p>The yarn prisma migrate dev command is used in development to create and apply database migrations based on changes to the Prisma schema. It automates the database schema update, generates the Prisma Client to match the schema, records a migration history, handles potentially destructive changes with interactive prompts, and utilizes a shadow database for safe testing. This command streamlines database iteration and client generation in the development environment, making it an essential tool for managing schema changes.</p><pre>yarn prisma migrate dev</pre><h4>Prisma module</h4><p>Refer to the <a href="https://docs.nestjs.com/recipes/prisma">documentation</a> to create a Nest module for Prisma ORM. For our example, create the below files in src/common folder.</p><pre>// src/common/prisma/prisma.service.ts<br>import { Injectable, OnModuleInit } from &#39;@nestjs/common&#39;<br>import { PrismaClient } from &#39;@prisma/client&#39;<br><br>@Injectable()<br>export class PrismaService extends PrismaClient implements OnModuleInit {<br>  async onModuleInit() {<br>    await this.$connect()<br>  }<br>}</pre><pre>// src/common/prisma/prisma.module.ts<br>import { Global, Module } from &#39;@nestjs/common&#39;<br>import { PrismaService } from &#39;./prisma.service&#39;<br><br>@Global()<br>@Module({<br>  providers: [PrismaService],<br>  exports: [PrismaService],<br>})<br>export class PrismaModule {}</pre><h4>Write Nest Models</h4><p>Including rich filtering, and sorting capabilities in a Graphql is difficult. There are also commonalities in writing the complex Input and Arg types for the everchanging models.</p><p>I have written an npm package for code-generation<a href="https://www.npmjs.com/package/nestjs-prisma-codegen">nestjs-prisma-codegen</a>. Also, find the <a href="https://github.com/karthickthankyou/nestjs-prisma-codegen">GitHub code here</a>.</p><p>In your src/ directory, Just run the command with the required model name.</p><p>npx nestjs-prisma-codegen User</p><p>That will generate all these files.</p><pre>├── common<br>│   ├── dtos<br>│   │   └── common.input.ts<br>├── models<br>│   └── users<br>│       ├── dto<br>│       │   ├── create-user.input.ts<br>│       │   ├── find.args.ts<br>│       │   ├── order-by.args.ts<br>│       │   ├── update-user.input.ts<br>│       │   └── where.args.ts<br>│       ├── entities<br>│       │   └── user.entity.ts<br>│       ├── users.module.ts<br>│       ├── users.resolver.ts<br>│       └── users.service.ts</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fjovialornateappaloosa&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fjovialornateappaloosa-the-predator-olivia-munn-confused&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FJovialOrnateAppaloosa-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1280" height="532" frameborder="0" scrolling="no"><a href="https://medium.com/media/da8a83815c53cdf9ca901a7e46325d0b/href">https://medium.com/media/da8a83815c53cdf9ca901a7e46325d0b/href</a></iframe><p>We generated only the essential ones. Let&#39;s look at the generated entity file.</p><pre>import { ObjectType } from &#39;@nestjs/graphql&#39;<br>import { User as UserType } from &#39;@prisma/client&#39;<br>import { RestrictProperties } from &#39;src/common/dtos/common.input&#39;<br><br>@ObjectType()<br>export class User implements RestrictProperties&lt;User, UserType&gt; {<br>  uid: string<br>  createdAt: Date<br>  name: string<br>}</pre><p>Notice I use a custom type RestrictProperties that implements the types generated by Prisma so that the Prisma schema and Nestjs types will always be in sync.</p><pre>export type RestrictProperties&lt;T, U&gt; = {<br>  [K in keyof T]: K extends keyof U ? T[K] : never<br>} &amp; Required&lt;U&gt;</pre><p>This will help to avoid adding extra properties or missing the existing ones from the Prisma schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_g9U5_w9xCEALQOrQKw_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrpC2hzkpgNbayw_b8MEMA.png" /></figure><blockquote>Syncing the Nestjs types with the Prisma types will be a breeze after every database migration!</blockquote><p>Once you implement the Prisma types to create nest types, You can feel free to add or remove services and resolvers.</p><h4>Finish the API</h4><p>Once you are happy with the resolvers and services. Add the modules to the app.module.ts file.</p><pre>@Module({<br>  imports: [<br>    ConfigModule.forRoot(),<br>    GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({<br>      driver: ApolloDriver,<br>      fieldResolverEnhancers: [&#39;guards&#39;],<br>      autoSchemaFile: join(process.cwd(), &#39;src/schema.gql&#39;),<br>      buildSchemaOptions: {<br>        numberScalarMode: &#39;integer&#39;,<br>      },<br>      introspection: true,<br>    }),<br><br>    PrismaModule,<br><br>    UsersModule,<br>    PostsModule,<br>    CommentsModule,<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><pre>yarn start:dev</pre><p>Your API is ready. 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umNvErfiLAcOcQ20clpGCA.png" /></figure><p>I prefer using apollo explorer for exploring the APIs as it requires much less typing.</p><p>Link: <a href="https://studio.apollographql.com/sandbox/explorer">https://studio.apollographql.com/sandbox/explorer</a></p><h4>Enable Cors</h4><p>The Graphql API we created is restricted to access from any other domain by default. Update the main.ts with the app.enableCors() adding ALLOWED_ORIGINS from the .env file.</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;<br>import { AppModule } from &#39;./app.module&#39;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule)<br>  const allowedOrigins = process.env.ALLOWED_ORIGINS.split(&#39;,&#39;)<br><br>  console.log(allowedOrigins)<br><br>  app.enableCors({<br>    origin: allowedOrigins,<br>    allowedHeaders: &#39;*&#39;,<br>    methods: &#39;*&#39;,<br>  })<br>  await app.listen(3000)<br>}<br>bootstrap()</pre><p>Sample .env file</p><pre>ALLOWED_ORIGINS=https://studio.apollographql.com,https://autospace.iamkarthick.com,http://localhost:3001</pre><h4>The in-depth argument types</h4><p>Graphql is not just about underfetching and overfetching. The nested arg types give us a crazy amount of flexibility.</p><p>Look at a sample OrderBy arg type.</p><pre>@InputType()<br>export class CommentOrderByWithRelationInput<br>  implements<br>    RestrictProperties&lt;<br>      CommentOrderByWithRelationInput,<br>      Prisma.CommentOrderByWithRelationInput<br>    &gt;<br>{<br>  @Field(() =&gt; Prisma.SortOrder, { nullable: true })<br>  id: Prisma.SortOrder<br>  @Field(() =&gt; Prisma.SortOrder, { nullable: true })<br>  text: Prisma.SortOrder<br>  @Field(() =&gt; Prisma.SortOrder, { nullable: true })<br>  postId: Prisma.SortOrder<br>  @Field(() =&gt; Prisma.SortOrder, { nullable: true })<br>  userId: Prisma.SortOrder<br>  @Field(() =&gt; PostOrderByWithRelationInput, { nullable: true })<br>  post: PostOrderByWithRelationInput<br>  @Field(() =&gt; UserOrderByWithRelationInput, { nullable: true })<br>  user: UserOrderByWithRelationInput<br>}</pre><p>Remember, the nested input types PostOrderByWithRelationInput and UserOrderByWithRelationInput are generated by <a href="https://www.npmjs.com/package/nestjs-prisma-codegen">nestjs-prisma-codegen</a>.</p><h4>Resolve Fields</h4><p>Let’s also satisfy the <strong>fetch-it-all-together</strong> facility Graphql API provides using ResolveField directive.</p><p>Inject the PrismaService in the constructor and we can use the powerful Prisma API to return information based on the parent data.</p><p>In this example, we return the author and comments that belong to the post.</p><pre>constructor(<br>  private readonly postsService: PostsService,<br>  private readonly prisma: PrismaService,<br>) {}<br><br>// ...<br><br>@ResolveField(() =&gt; User)<br>author(@Parent() parent: Post) {<br>  return this.prisma.user.findUnique({ where: { uid: parent.authorId } })<br>}<br><br>@ResolveField(() =&gt; [Comment])<br>comments(@Parent() parent: Post) {<br>  return this.prisma.comment.findMany({ where: { postId: parent.id } })<br>}</pre><h4>Demo!</h4><p>Our API has</p><ul><li>Mutations with validated Data Transfer Objects.</li><li>Rich argument types with filtering, sorting, and pagination capabilities.</li><li>Resolve fields to fetch related data together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_VYWpf7xyx3_Ozuxazvyw.png" /></figure><p>Next time you come across a Graphql API tutorial, notice how extensive the filtering and sorting capabilities of that. 90% of the tutorials don&#39;t go beyond implementing skip and limit arguments.</p><p>Thanks for reading.</p><p>Code: <a href="https://github.com/karthickthankyou/nestjs-prisma-simple-graphql-api">https://github.com/karthickthankyou/nestjs-prisma-simple-graphql-api</a></p><p>Happy coding. 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55cf6e6e987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Simple Steps to Streamline Your Development: Creating a Monorepo Setup with Nx & Yarn Workspaces.]]></title>
            <link>https://karthickragavendran.medium.com/streamline-your-development-with-nx-and-yarn-workspaces-building-a-monorepo-setup-with-nestjs-and-e3d0d560decf?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3d0d560decf</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[eslint]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 08:14:38 GMT</pubDate>
            <atom:updated>2023-08-13T04:57:14.024Z</atom:updated>
            <content:encoded><![CDATA[<p>With the rise of efficient build systems like Nx and Turborepo, creating and managing monorepos have become simpler.</p><p>Let&#39;s create a simple monorepo setup that has a NestJS project and NextJS project with shared linting, type-checking, formatting, and caching capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK3_6-Duf1SKJS8PiJ6pvg.jpeg" /></figure><h3>1. Setup yarn workspaces</h3><p>Create a folder and open it with VSCode.</p><pre>mkdir next-nest-monorepo<br><br>code next-nest-monorepo // Needs code command to be installed in path in vscode. Or manually open the folder.<br><br>yarn init -y<br><br>mkdir apps libs // Create folders for apps and libs</pre><p>Update the package.json of the newly created nodejs project with the below.</p><pre>{<br>  &quot;name&quot;: &quot;next-nest-monorepo&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;private&quot;: &quot;true&quot;,<br>  &quot;workspaces&quot;: {<br>    &quot;packages&quot;: [<br>      &quot;apps/*&quot;,<br>      &quot;libs/*&quot;<br>    ]<br>  }<br>}</pre><ul><li>&quot;private&quot;: &quot;true&quot;indicates that the monorepo is private, and it won&#39;t be published to a public registry like npm.</li><li>&quot;workspaces&quot;: {&quot;packages&quot;: [&quot;apps/*&quot;<a href="https://medium.com/a7dbafe9b1cf4257becfee675b708b43?pvs=25">, “libs/*”</a>]} specifies the location of the packages in the monorepo. Here, the &quot;apps/*&quot; pattern indicates that all packages in the apps directory should be included as workspaces. Workspaces are a Yarn feature that allows you to manage multiple packages in a single repository.</li></ul><h4>Git</h4><p>Initialize and do the first commit.</p><pre>git init<br><br>// Create a .gitignore<br>echo &quot;node_modules \nbuild \ndist \n.next \n.env&quot; &gt;&gt; .gitignore<br><br>git add .<br>git commit -m &#39;initial commit&#39;</pre><h4>Create projects in “apps/*”</h4><p>Create an apps directory and create NextJS and NestJS applications inside it.</p><pre>// Create apps directory.<br>mkdir apps<br>cd apps<br><br>// Next<br>yarn create next-app web --ts <br><br>// Nest<br>npx nest new api --package-manager=yarn</pre><h4>Some fixes</h4><p>Now we have a yarn workspace setup with both our backend and frontend projects inside it. I had to address a few problems.</p><p>If you face issues working with nestjs in a monorepo, you may need to avoid adding nestjs dependencies to the root node_modules. You can update the workspaces in the package.json as below.</p><pre>&quot;workspaces&quot;: {<br>  &quot;packages&quot;: [<br>    &quot;apps/*&quot;<br>  ],<br>  &quot;nohoist&quot;: [<br>    &quot;**/@nestjs&quot;,<br>    &quot;**/@nestjs/**&quot;<br>  ]<br>}</pre><blockquote>“nohoist” enables workspaces to consume 3rd-party libraries <strong>not yet compatible</strong> with its hoisting scheme. The idea is to disable the selected modules from being hoisted to the project root. They were placed in the actual (child) project instead, just like in a standalone, non-workspaces, project.</blockquote><p>I also found that the NestJS project creates a separate .git when we initialize it. Remove it.</p><pre>cd apps/api<br>rm -rf .git </pre><h3>2. Setup Nx: The build system</h3><p>We are going to use Nx as the build system for our yarn monorepo.</p><pre>npx add-nx-to-monorepo</pre><p>Answer the questionnaire. I also answered <strong>yes</strong> to “Enable distributed caching to make your CI faster?”.</p><p>This creates a nx.json file in the root.</p><pre>{<br>  &quot;tasksRunnerOptions&quot;: {<br>    &quot;default&quot;: {<br>      &quot;runner&quot;: &quot;@nrwl/nx-cloud&quot;,<br>      &quot;options&quot;: {<br>        &quot;cacheableOperations&quot;: [&quot;build&quot;],<br>        &quot;accessToken&quot;: &quot;******&quot;<br>      }<br>    }<br>  },<br>  &quot;defaultBase&quot;: &quot;master&quot;<br>}</pre><p>Let’s try using the Nx commands. The below one helps us to run all build commands in our monorepo.</p><h4>Executing commands with Nx</h4><pre>yarn nx run-many --target=build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vv0HTtnqZjHqnli7YB9dug.png" /></figure><p>Now run the command again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2_B0mHHqw8V_v5Lw6KOnw.png" /></figure><p>The built time for the two applications went from to 0.48 seconds to 11.75 seconds How cool is that? 😎⚡️</p><h3>3. Validation: Typescript | ESLint | Prettier</h3><p>To ensure that all of our projects are validated uniformly, create a validation script in our root directory.</p><h4>Prettier</h4><p>Install prettier. We need to add — ignore-workspace-root or -W to ignore the workspace root check.</p><pre>yarn add -D prettier -W</pre><p>Create a .prettierrc file in the root.</p><pre>{<br>  &quot;singleQuote&quot;: true,<br>  &quot;trailingComma&quot;: &quot;all&quot;,<br>  &quot;semi&quot;: false<br>}</pre><h4>Prettier plugins:</h4><p>I also added prettier-plugin-organize-imports <a href="https://github.com/simonhaenisch/prettier-plugin-organize-imports">plugin</a> that helps remove unused imports and sort imports on save. It is a huge time save for me.</p><pre>yarn add -D prettier-plugin-organize-imports</pre><p>Automatic plugin discovery happens for prettier &lt; 3. For version above 2, refer to the <a href="https://github.com/simonhaenisch/prettier-plugin-organize-imports">documentation</a>.</p><h4>Format scripts</h4><p>Add scripts in the root package.json file for checking and fixing format issues.</p><pre>  &quot;scripts&quot;: {<br>    &quot;prettier&quot;: &quot;prettier  \&quot;{apps,libs}/**/*.{ts,tsx,js,json}\&quot; --ignore-path .gitignore&quot;,<br>    &quot;format:check&quot;: &quot;yarn prettier --check&quot;,<br>    &quot;format:write&quot;: &quot;yarn prettier --write&quot;,<br>  }</pre><p>Now we can run formatting for the whole monorepo from the root.</p><pre>yarn format:check<br>yarn format:write</pre><h4>Type-checking</h4><p>Add the below tsc commands in the respective files. You will also need to add tsc script to the package.json of the libs you create.</p><pre>// <strong>apps/api/package.json</strong> -&gt; &quot;scripts&quot;<br>&quot;tsc&quot;: &quot;tsc&quot;</pre><pre>// <strong>apps/web/package.json</strong> -&gt; &quot;scripts&quot;<br>&quot;tsc&quot;: &quot;tsc&quot;</pre><pre>// <strong>package.json</strong> -&gt; &quot;scripts&quot;<br>&quot;tsc&quot;: &quot;nx run-many --target=tsc&quot;</pre><p>Now, we can enjoy type-checking the whole monorepo from the root.</p><pre>yarn tsc</pre><h4>Linting</h4><p>Both our nestjs and nextjs have eslint setup for us with alint script. Add a common lint script with Nx’s run-many feature in the root package.json.</p><pre>&quot;lint&quot;: &quot;nx run-many --target=lint&quot;,</pre><pre>yarn lint // Runs linting in both our projects.</pre><h4>Run them all parallel together</h4><p>In huge projects, each of these commands can take a significant amount of time. Let&#39;s create a validate script that runs all three scripts in parallel. You can add other scripts as well liketest.</p><p>Install npm-run-all in the root.</p><pre>yarn add -D npm-run-all -W</pre><p>Add validate script in the root package.json file.</p><pre>&quot;validate&quot;: &quot;run-p lint tsc format:check&quot;,</pre><p>Now the scripts look like below.</p><pre>  &quot;scripts&quot;: {<br>    &quot;prettier&quot;: &quot;prettier  \&quot;{apps,libs}/**/*.{ts,tsx,js,json}\&quot; --ignore-path .gitignore&quot;,<br>    &quot;format:check&quot;: &quot;yarn prettier --check&quot;,<br>    &quot;format:write&quot;: &quot;yarn prettier --write&quot;,<br>    &quot;lint&quot;: &quot;yarn nx run-many --target=lint&quot;,<br>    &quot;tsc&quot;: &quot;yarn nx run-many --target=tsc&quot;,<br>    &quot;prevalidate&quot;: &quot;yarn format:write&quot;,<br>    &quot;validate&quot;: &quot;run-p format:check lint tsc&quot;<br>  }</pre><p>Note I also added a prevalidate script that runs before the validate which runs format:write for us. At this point we can remove the format:check in validate. But I’m going to leave it there.</p><p>Run one command, sit back, and enjoy the automation 😎.</p><pre>yarn validate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKT1rQ1o04hB-qufbqv-9Q.png" /></figure><p>It all took 3.5 seconds.</p><p>Want to optimize more?</p><p>I added lint and tsc to the “cacheableOperations” in nx.json .</p><pre>{<br>  &quot;tasksRunnerOptions&quot;: {<br>    &quot;default&quot;: {<br>      &quot;runner&quot;: &quot;@nrwl/nx-cloud&quot;,<br>      &quot;options&quot;: {<br>        &quot;cacheableOperations&quot;: [&quot;build&quot;, &quot;<strong>lint</strong>&quot;, &quot;<strong>tsc</strong>&quot;],<br>        &quot;accessToken&quot;: &quot;******&quot;<br>      }<br>    }<br>  },<br>  &quot;defaultBase&quot;: &quot;master&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYhK_FUQktKBtKDj8si1KA.png" /></figure><blockquote>Our validate script went from 3.5 seconds to 0.74 seconds.</blockquote><p>Learn how Nx does the caching in this <a href="https://nx.dev/concepts/how-caching-works">official documentation</a>.</p><h3>4. Run validation on the Pre-commit hook.</h3><p>We have a powerful validation script. Let&#39;s run that before every commit by usinghusky and lint-staged.</p><p>Initialize husky.</p><pre>npx husky-init &amp;&amp; yarn</pre><p>This will create a .husky folder with pre-commit hook.</p><p>Install lint-staged in the root.</p><pre>yarn add -D lint-staged -W</pre><p>Create a lint-staged.config.js in the root.</p><pre>module.exports = {<br>  &#39;*.{ts,tsx}&#39;: (filenames) =&gt; [&#39;yarn validate&#39;],<br>}</pre><p>Notice that this also runsformat:write before validating due to the prevalidate script.</p><p>Modify the pre-commit file in .husky to below.</p><pre>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br><br>npx lint-staged</pre><p>That’s all. Please feel free to play around inducing type, linting, and formatting issues anywhere in the codebase and see if you can commit.</p><p>I created a type/lint error in my _app.tsx file.</p><pre>  const a = 5<br>  a = &#39;str&#39;</pre><p>Then, I tried to commit</p><pre>git add .<br><br>git commit -m &#39;testing pre-commit&#39;</pre><p>The commit fails as expected. 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cT5174Ft8YruCsg7Z8o0Q.png" /></figure><p>This drastically improves the quality of commits and stops dirty commits in the developers&#39; local environment.</p><p>Fix the type error and your commit will go through.</p><h4>Fire exit?</h4><p>What if your building is on fire and you are stuck with a type error that stops you from pushing your code?</p><p>Use --no-verify.</p><pre>git commit -m &#39;testing no-verify&#39; --no-verify</pre><p>This will skip the pre-commit validation altogether in emergency situations.</p><h4>Conclusion</h4><p>We have done a lot today. We created a mono repo. Set up Nx build system to run cacheable commands. We created a validate script with a pre-commit hook facility. All these setups will help us keep all our projects in one place safe. And safe codebases make happy developers.</p><p>Happy coding! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3d0d560decf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query in SSR starring Graphql-Codegen]]></title>
            <link>https://karthickragavendran.medium.com/react-query-in-ssr-starring-graphql-codegen-54c0dc4b07b4?source=rss-1dc8778cadf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/54c0dc4b07b4</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[codegen]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Karthick Ragavendran]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 11:52:05 GMT</pubDate>
            <atom:updated>2021-12-09T11:52:05.508Z</atom:updated>
            <content:encoded><![CDATA[<p>Graphql is awesome. Need to make it more awesome?</p><h4>What makes Graphql more awesome?</h4><p>Consider the below type Character.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dae60e84c462d9bb967cd6e442e5add/href">https://medium.com/media/1dae60e84c462d9bb967cd6e442e5add/href</a></iframe><p>Imagine we query 4 properties from the type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd6b2fc626af322f2850c1ff13cf3494/href">https://medium.com/media/cd6b2fc626af322f2850c1ff13cf3494/href</a></iframe><p>Now, if we can do the below, that makes working with Graphql more awesome!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZD_SAuLwky9ctYHB9x9RA.png" /></figure><blockquote>In this article, we will see how to get <strong>up-to-date type checking </strong>and auto-completion with serverside data fetching synched to the client side cache.</blockquote><h4>Repository</h4><p>Find the repository for finished code below.</p><p><a href="https://github.com/karthickthankyou/next-react-query-graphql-codegen">https://github.com/karthickthankyou/next-react-query-graphql-codegen</a></p><h4>Create a new next app.</h4><pre>npx create-next-app --ts</pre><h4>Install dependencies</h4><pre>npm i <strong>graphql</strong><br>npm i -D <strong>@graphql-codegen/cli</strong></pre><h4>Initialize the project</h4><pre>npx graphql-codegen init</pre><h4>Answer a few simple questions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6KQrmafpKljY3GEj28QSw.png" /></figure><p>Note the two plugins Typescript and Typescript Operations in Pick plugins.</p><h4>Legacy peer dependency</h4><p>While installing the dependencies with npm i, You may encounter the Could not resolve dependency problem with the version of graphql.</p><p>This problem can be worked around by downgrading your npm version to 6.x. But use the --legacy-peer-deps flag.</p><pre>npm i --legacy-peer-deps</pre><h4>Install React Query</h4><p>The <a href="https://www.graphql-code-generator.com/plugins/typescript-react-query">official documentation</a> of graphql-codegen plugin for the react-query is elaborate. Check that out for more details.</p><pre>npm i react-query<br>npm i -D  @graphql-codegen/typescript-react-query</pre><h4>Update Codegen.yml</h4><p>Update the codegen.yml file in the root to resemble the below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/130200b112f4466ffca6a18c6f412fb8/href">https://medium.com/media/130200b112f4466ffca6a18c6f412fb8/href</a></iframe><ul><li>exposeFetcher: By default, codegen generates custom<strong> hooks </strong>for our queries and mutations. But hooks can not be used with getStaticProps or getServersideProps. This property was <a href="https://github.com/dotansimha/graphql-code-generator/issues/5526">introduced</a> to enable a fetcher function that we can use in the server-side functions. Ex: useGetCustomers.fetcher().</li><li>exposeQueryKeys: This property enables .getKey(). We use it as the key for the react query without having to manually give a string.</li><li>Content-Type fetchParams: The Content-Type by default is set to text/html for the response header and text/plain for the request. That will get us the POST body missing. Did you forget use body-parser middleware? error. So update this to application/json.</li><li>pureMagicComment: This is to enforce tree-shaking.</li></ul><h4>Sample query</h4><p>Create a query.graphql file. You can name this anything you want as long as it matches src/**/*.graphql that we provided in the documents field in codegen.yml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd6b2fc626af322f2850c1ff13cf3494/href">https://medium.com/media/cd6b2fc626af322f2850c1ff13cf3494/href</a></iframe><h4>Generate!</h4><p>Execute the below command to see your types and react query hooks generated for us!</p><pre>npm run gql:codegen</pre><pre>// or</pre><pre>npx graphql-codegen --config codegen.yml</pre><h4>React Query — Hydrate</h4><p>React query suggests two ways to query data in SSR. Read about that in detail <a href="https://react-query.tanstack.com/guides/ssr">here</a>.</p><p>We are going to use the hydration technique.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5931e501690e1131fc1d7757bbdaa443/href">https://medium.com/media/5931e501690e1131fc1d7757bbdaa443/href</a></iframe><h4>React Querying in getStaticProps</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bcab5a8ce622e3965587ccafc6a13dd/href">https://medium.com/media/8bcab5a8ce622e3965587ccafc6a13dd/href</a></iframe><p>That’s it.</p><p>Try removing the client-side fetching of useGetCharacters (lines: 21, 22) and you will still see the data being stored on the client-side using the dev tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPtKYRCh86UI5t0tqt8c4w.png" /></figure><p>How cool is that?</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54c0dc4b07b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>