avatarDr Mehmet Yildiz

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5801

Abstract

cookie.</li><li><code>secure: true</code> ensures that the cookie is only sent over secure, encrypted connections (HTTPS). but since most testing environments are on localhost, it is allowed</li></ul><p id="6bc1">then executing this action looks like:</p><div id="e2cb"><pre><span class="hljs-keyword">import</span> { storeToken } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/actions"</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">onSubmit</span>(<span class="hljs-params">formData</span>) { <span class="hljs-title function_">setIsLoading</span>(<span class="hljs-literal">true</span>); <span class="hljs-keyword">try</span> { <span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> http.<span class="hljs-title function_">post</span>(<span class="hljs-string">/auth/login</span>, formData);

  <span class="hljs-keyword">await</span> <span class="hljs-title function_">storeToken</span>(resp.<span class="hljs-property">data</span>);

  router.<span class="hljs-title function_">push</span>(<span class="hljs-string">"/dashboard"</span>);

  <span class="hljs-title function_">toast</span>({
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Login Successful"</span>,
  });
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">"error logging in"</span>, error);
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-title function_">setIsLoading</span>(<span class="hljs-literal">false</span>);
}

}</pre></div><p id="173a">After testing this check your cookie storage in devtools and the token should be set:</p><figure id="de3a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*VxsyZ7KTXg_XygebpIfq1Q.png"><figcaption></figcaption></figure><p id="7f8d">Now let’s move on to using the token to communicate with our API.</p><h1 id="ad3b">2. Accessing the Token</h1><p id="3425">So accessing the token is different depending on the context. If you are accessing it on the server it looks like:</p><div id="ba24"><pre>import {cookies} <span class="hljs-keyword">from</span> <span class="hljs-string">"next/headers"</span>;

<span class="hljs-keyword">const</span> authToken = cookies().<span class="hljs-keyword">get</span>(<span class="hljs-string">"accessToken"</span>)?.<span class="hljs-keyword">value</span> </pre></div><p id="636a">In the Client side, because we set <code>httpOnly: true</code> . How do we now access our jwt? That’s where creating an api route comes in. It would have been really cool to have a server action for retrieving the token but we don’t have that yet. “fix up Next.js team”!</p><p id="dc9e">Docs for api routes using the app router <a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers">here</a></p><p id="c93d">so the gist is a folder structure of <code>app/api/auth/token/route.ts</code> resolves to an endpoint with path of <code>/api/auth/token</code> . Now in the route.ts file we write:</p><div id="916b"><pre>import { cookies } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/headers'</span>

export async <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GET</span>(<span class="hljs-params">request: Request</span>) </span>{ <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">authToken</span> = <span class="hljs-title function_ invoke__">cookies</span>().<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">'accessToken'</span>)?.value <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">headers</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Headers</span>(); headers.<span class="hljs-title function_ invoke__">append</span>(<span class="hljs-string">"Authorization"</span>, authToken);

<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">response</span> = await <span class="hljs-title function_ invoke__">fetch</span>(`${process.env.NEXT_PUBLIC_API_URL}/user`,{
  <span class="hljs-attr">headers</span>: headers
}
<span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">401</span>) {
  <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">refreshPayload</span> = {
    <span class="hljs-string">"refresh_token"</span>: <span class="hljs-title function_ invoke__">cookies</span>().<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">'refreshToken'</span>)?.value
  }
  <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">res</span> = await <span class="hljs-title function_ invoke__">fetch</span>(`${process.env.NEXT_PUBLIC_API_URL}/refresh-token, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
    },
     <span class="hljs-attr">body</span>: JSON.<span class="hljs-title function_ invoke__">stringify</span>(refreshPayload),
  }
  
  <span class="hljs-keyword">const</span> jsonData = await res.<span class="hljs-title function_ invoke__">json</span>()
  
  <span class="hljs-title function_ invoke__">cookies</span>().<span class="hljs-title function_ invoke__">set</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">"acce

Options

ssToken"</span>, <span class="hljs-attr">value</span>: jsonData.token, <span class="hljs-attr">httpOnly</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">sameSite</span>: <span class="hljs-string">"strict"</span>, <span class="hljs-attr">secure</span>: <span class="hljs-literal">true</span>, })

  <span class="hljs-title function_ invoke__">cookies</span>().<span class="hljs-title function_ invoke__">set</span>({
      <span class="hljs-attr">name</span>: <span class="hljs-string">"refreshToken"</span>,
      <span class="hljs-attr">value</span>: jsonData.refresh_token,
      <span class="hljs-attr">httpOnly</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">sameSite</span>: <span class="hljs-string">"strict"</span>,
      <span class="hljs-attr">secure</span>: <span class="hljs-literal">true</span>,
  })
} 
<span class="hljs-keyword">const</span> resData = {
    <span class="hljs-attr">token</span>: <span class="hljs-title function_ invoke__">cookies</span>().<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">'accessToken'</span>)?.value
}



<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Response</span>(JSON.<span class="hljs-title function_ invoke__">stringify</span>(resData), {
    <span class="hljs-attr">status</span>: <span class="hljs-number">200</span>,
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
    },
})

}</pre></div><p id="66db">Now let’s break down what this api route does:</p><ul><li>we retrieve the jwt from the cookie store</li><li>we make a request to /user on our api to check if the token is still valid. /user can be replaced with any protected route on your api</li><li>if we receive the <code>unauthorized(401)</code> error code we send a request to get a new token pair with our refresh token.</li><li>then we return the valid token back to the client for use.</li></ul><p id="260f">Now, to make use of this API route we can write an axios interceptor like so:</p><div id="b457"><pre>axiosInstance.<span class="hljs-property">interceptors</span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">async</span> (config) => { <span class="hljs-keyword">if</span> (config.<span class="hljs-property">url</span>?.<span class="hljs-title function_">includes</span>(<span class="hljs-string">"auth"</span>)) { <span class="hljs-keyword">return</span> config }

    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">'/api/auth/token'</span>)
    <span class="hljs-keyword">const</span> resData = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">json</span>()
    <span class="hljs-keyword">const</span> token = resData?.<span class="hljs-property">token</span>

    config.<span class="hljs-property">headers</span>![<span class="hljs-string">'Authorization'</span>] = <span class="hljs-string">"Bearer "</span> + token
     <span class="hljs-keyword">return</span> config
},
<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error)
}

)</pre></div><p id="8f27">What this interceptor does is: “if the app is making a request to an auth route like <code>/auth/login</code> , <code>/auth/signup</code> no token is sent along with the request but if it is to a protected route it fetches the access token from our api route and passes it in the <code>Authorization</code> header.</p><h2 id="c7b2">Further reading:</h2><p id="fb63">This article was greatly inspired by:</p><div id="b5f3" class="link-block"> <a href="https://javascript.plainenglish.io/next-js-secure-authentication-using-http-only-cookie-graphql-or-rest-a4ef94cec9e8"> <div> <div> <h2>Next.js Secure Authentication Using http-only Cookie (GraphQL or REST)</h2> <div><h3>When it comes to user authentication we need to make sure our application is secured from any potential threats. To…</h3></div> <div><p>javascript.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*FBBZ5ksEs057sEfEkcl42g.png)"></div> </div> </div> </a> </div><p id="7edc">If you want to see how to do this with graphql. or you are working on older versions of Next without server actions, I suggest the article.</p><p id="948d">Thanks for reading and if you have any questions, drop them in the comments.</p><p id="50be">Happy building!🚀</p><h1 id="d403">Stackademic</h1><p id="3a1b"><i>Thank you for reading until the end. Before you go:</i></p><ul><li><i>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</i></li><li><i>Follow us on <a href="https://twitter.com/stackademichq"><b>Twitter(X)</b></a>, <a href="https://www.linkedin.com/company/stackademic"><b>LinkedIn</b></a>, and <a href="https://www.youtube.com/c/stackademic"><b>YouTube</b></a><b>.</b></i></li><li><i>Visit <a href="http://stackademic.com/"><b>Stackademic.com</b></a> to find out more about how we are democratizing free programming education around the world.</i></li></ul></article></body>

Editorial bulletin

ILLUMINATION Book Chapters

Editorial Bulletin #5 — Let’s Meet New Contributors

image designed by Dr Mehmet Yildizdigitalmehmet.com

ILLUMINATION opens a new chapter on Medium. Published authors are welcome to join this new journey.

ILLUMINATION Book Chapters is diverse and inclusive.

This is the fifth editorial bulletin for ILLUMINATION Book Chapters. I am grateful for your inspiring feedback on previous bulletins.

Several chapters have been curated by Medium and distributed to readers of various topics.

My purpose in this post is to provide daily updates on this initiative.

On the first anniversary of ILLUMINATION, 19 March 2021, I introduced this valuable initiative called ILLUMINATION Book Chapters. This is a first a kind service on Medium.

Purpose of ILLUMINATION Book Chapters

1 — Published authors can gain new readers via their repurposed book chapters. They can also earn income from their published content on their Medium.

2 — Published authors can gain new followers and beta readers who can provide feedback for their manuscripts.

3 — Aspiring writers can gain create manuscripts derived from their published stories. They can transfer them into the ILLUMINATION Book Chapters, obtain reader reviews, and publish them as books later.

Let me introduce the published chapters

Dr Mehmet Yildiz

Powerful Life-Changing Hacks That Truly Transformed My Life

Chapter 1

Chapter 2

Chapter 3

Simon Dillon

Peaceful Quiet Lives

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Øivind H. Solheim

The Happiest Town in the World

Chapter 1

Chapter 2

Nicole Maharaj

Chapter 1

Chapter 2

Ulf Wolf

Part 1

Annelise Lords

The Yellow Hibiscus

Chapter 1

Akarsh Nalawade

Beamish And Bhaji

Chapter 1

Floyd Mori

Book review

Part 1

Christopher Akinlade

While She Was Away

Chapter 1

Chapter 2

Sahil Patel

A Girl Who Is Looking For Freedom

Introduction

Claudia Stack

Willow

Chapter 1: The Inside Door

Chapter 2: The Stable

Chapter 3: The Reckoning

Chapter 4: Maggie Arrives

Chapter 5: Sonia Drifts

Chapter 6: Maggie and Sarah

Chapter 7: The Celtic Cross

Chapter 8: The Picture

Chapter 9: The Pull of the Hudson

The Garrulous Glaswegian

Sex Saved Me From a Christian Cult

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Phil Truman

Skins Game

Part 1

Part 2

Part 3

Shashi Sastry

Philosophy of Life Instinct

Prologue

Introduction

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Chapter 5

As an example, some chapters of Shashi’s book were earlier published on ILLUMINATION. Now, he is transferring the chapters to ILLUMINATION Book Chapters to expose his content to a new audience.

Phil Rossi

Soldier Hill

Chapter 1

Chapter 2

Karen Madej

Two Little Girls Watch Mommy Leave Them

Chapter 1 — Sarah

Chapter 2 — Miles

Chapter 3 — Frances

And please enjoy our first poetry submission today.

Ivette Cruz

My Voice Awakens

Page 1

Book Reviews

You can also publish book reviews, your own one or other books.

Please check a sample self-review for one of my books.

Chapter Reviews

Jay Toran reviewed five chapters and created a story on ILLUMINATION.

Thoughts And Invitations from Editors

Maria Rattray

If a window of opportunity appears, don’t pull down the shade. So let me introduce to you, one window of opportunity! If everyone on Illumination is as excited as I am, this most recent innovation of Dr Mehmet Yildiz should go off like a rocket. With so many readers and writers, there’s surely amongst us, a percentage of Ernest Hemingway, or Jane Harper (a new Aussie writer), aspirants, waiting with bated breath, not just hoping for success, but also waiting for the door of opportunity to open. There’s talent amongst us, lots of it, and if we harness this opportunity, who knows where it might take us? But you know, talent we may have on various levels, but getting a book to publication, to be read by the masses, so that we can write even more in the south of France, or wherever takes your fancy, ( ILLUMINATION cares not where you write), can be little more than the stuff of dreams, unless you are prepared for some serious work. Yet there is huge opportunity here, if we are prepared to go for it…to be at the coalface of such an opportunity, to be seen and valued by a smaller, but meaningful group of people, readers and writers alike, people who value and promote each other, is exciting. You don’t get much of that in the big, bad world. To be published by a large company is at best, the stuff of dreams, to self-publish on Amazon is wonderful, and within the morass you can be lucky, but the flip side of that is understanding and paying for, things like marketing and book covers. That’s big money we’re talking about!

The Garrulous Glaswegian

I‘ve just come upon a new and intriguing proposition. In its first year, ILLUMINATION gained an incredible 90,000 followers, making it one of the fastest-growing and most successful publications on Medium. You can learn more about that in Dew Langrial ’s piece here. Dr Yildiz has a busy, inventive mind, and is always looking for clever ideas to support writers. Enter his latest project ILLUMINATION Book Chapters. So I’ve plunged headfirst into Dr Yildiz’ new endeavour, and am proud to have been the first writer added to the fold. And just for fun, I made a wee video to explain why ILLUMINATION Book Chapters is such a great idea. For the last couple of months, I’ve mostly been importing work to Medium from other sites, and have created almost no new stories for Medium. My subscription ran out this month and I swore I wouldn’t be renewing it. I had deleted aver 100 articles from the site and rehomed many of them. And yet, here I am again! Only ILLUMINATION could tempt me back into the Medium fold. I’ve never known a more a positive, engaging and worthwhile forum. I’m genuinely intrigued by this new idea, and for the first time in a long time, I’m excited about adding fresh content to Medium.

Britni Pepper

ILLUMINATION is breaking new ground here. With the introduction of ILLUMINATION Book Chapters, a longer, richer, and deeper reading experience becomes available on Medium. Our new publication has nothing but longform stories, divided up into chapters. Here the writers spread out their biggest and best work, and readers can immerse themselves in the experience, coming up to draw the occasional breath of the everyday world when it’s time to click on the link to the next chapter. Given the caliber of our writers, I’m expecting great things from ILLUMINATION Book Chapters. Great reading, that goes without saying, but here is the place for novels, themed collections, textbooks on specialised topics, detailed exploration into history, travel, the world, and the cosmos. Maybe some of the masterworks to come will be the basis of movies, screens full of titles on Amazon, real printed books on library shelves. Forget “maybe”. It’s a certainty. Some of what you read here on ILLUMINATION Book Chapters will end up as actual books in a reader’s hands. As a published author myself, I’ve serialised books here on Medium, and I was delighted to find in my Amazon sales report that somebody had ordered a printed copy of my naughty little Route 66 adventure story.

Dr Preeti Singh

Illumination has the policy of inclusivity. Dr. Mehmet Yildiz is very clear that everybody should get a chance to publish their stories. People from all walks of life, different countries, nationalities are welcome to this family. Those who do not have English as their first language are also given a chance to express their views and can be mentored with the support of editors. This publication is also inclusive. It gives us all a chance to express something. Everyone cannot be an author. Some are readers. We can write a book review about something that we have read and have it published and, in this way, we get a chance to express ourselves. Many authors asked on our Slack Channel if they could write longer articles and if they would be published in Illumination. Dr.Mehmet thought about this and a new baby was born out of Illumination. It is called ILLUMINATION Book Chapters. Illumination book chapters have some special qualities

Karen Madej

Hello lovelies, this week is all about my favourite, FICTION! A special edition today to celebrate the launch of a new ILLUMINATION family publication. If you haven’t spotted Dr Mehmet Yildiz’s ILLUMINATION Book Chapters publication invitation yet, I suggest you give it a read. Especially the authors of the chapters I’m reading and sharing here. Because your chapters are here means they are not in ILLUMINATION Book Chapters. You might like to join up as a writer and submit your chapters. There are advantages to getting in early, you get noticed! Keep submitting your chapters and you’ll keep getting noticed. It worked for me on ILLUMINATION. All I did was show up every week, once, twice or three plus time for a year.

Linda Kowalchek

“I have wanted to write a book since I was a teenager. I remember sitting at the desk in my bedroom with my powder-blue plastic Smith Corona manual typewriter in front of me. I was ready. But then I realized that I had no idea what to write about, so I went back downstairs and watched Luke and Laura’s wedding on General Hospital. But I digress. About 40 years have passed, and I still haven’t written a book. I publish my stories on Medium using an outdated MacBook Air, which at least is a step up from a manual typewriter. But as far as my progress with writing a book, I am stagnating. I’m afraid that I will finally write my book, and it will suck.”

Jay Toran

“For all those who’ve jumped the gun and started typing their first chapters into the laptop, you’ve got to understand a few things: And it goes back to the same problem of editors having a limited amount of time. No amount of frenzied typing is going to get around this problem. I’m not an editor, but I’ve done some editing for a couple of the big names here on ILLUMINATION. So I can pretty well guess that they just are not going to take submissions that have half-thought-out plots. And grammar errors? I just don’t believe they’ll have the time to even consider those kinds of stories. As a matter of fact, it’s likely they won’t even look at the first chapters of newbie authors before seeing a fairly well-developed outline of what the book is going to be about. I think you young authors should understand the realities of the time-pressure the ILLUMINATION editors are under.”

I hope you will enjoy reading these great chapters.

If you have books or manuscript, please contact us by sending a request with your Medium account ID to contribute to ILLUMINATION Book Chapters. We will publish your book chapters in story format. Not only do you generate passive income, but you also gain new readers.

As we grow and scale our services to more authors, we will need more editors for this publication. Please show your interest by leaving a comment on this bulletin or contact me.

Thank you for your support and for reading my bulletins.

It is a pleasure for me to serve both published and aspiring authors.

Dr Mehmet Yildiz

Chief Editor

image designed by Dr Mehmet Yildizdigitalmehmet.com

If you enjoyed this story, you might also check our curated and featured stories compiled by ILLUMINATION daily.

As a new reader, you might check my holistic health and well-being stories reflecting on my reviews, observations, and decades of sensible experiments. I write about health as it matters. I believe health is all about homeostasis.

I enjoy informing my readers about hormonal intelligence by writing about neurotransmitters such as dopamine, serotonin, oxytocin, GABA, acetylcholine, norepinephrine, adrenaline, glutamate, and histamine.

One of my goals as a writer is to raise awareness about the causes and risk factors of prevalent diseases that can lead to suffering and death for a large portion of the population.

To raise awareness about health issues, I have written several articles that present my holistic health findings from research, personal observations, and unique experiences. Below are links to these articles for easy access.

Metabolic Syndrome, Type II Diabetes, Fatty Liver Disease, Heart Disease, Strokes, Obesity, Liver Cancer, Autoimmune Disorders, Homocysteine, Lungs Health, Pancreas Health, Kidneys Health, NCDs, Infectious Diseases, Brain Health, Dementia, Depression, Brain Atrophy, Neonatal Disorders, Skin Health, Dental Health, Bone Health, Leaky Gut, Leaky Brain, Brain Fog, Chronic Inflammation, Insulin Resistance, Elevated Cortisol, Leptin Resistance, Anabolic Resistance, Cholesterol, High Triglycerides, Metabolic Disorders, Gastrointestinal Disorders, and Major Diseases.

I also wrote about valuable nutrients. Here are the links for easy access:

Lutein/Zeaxanthin, Boron, Urolithin, taurine, citrulline malate, biotin, lithium orotate, alpha-lipoic acid, n-acetyl-cysteine, acetyl-l-carnitine, CoQ10, PQQ, NADH, TMG, creatine, choline, digestive enzymes, magnesium, zinc, hydrolyzed collagen, nootropics, pure nicotine, activated charcoal, Vitamin B12, Vitamin B1, Vitamin D, Vitamin K2, Omega-3 Fatty Acids, N-Acetyl L-Tyrosine, and other nutrients to improve metabolism and mental health.

Disclaimer: Please note that my posts do not include professional or health advice. I document my reviews, observations, experience, and perspectives only to provide information and create awareness.

I publish my lifestyle, health, and well-being stories on EUPHORIA. My focus is on metabolic, cellular, mitochondrial, and mental health. Here is my collection of Insightful Life Lessons from Personal Stories.

If you enjoy writing and storytelling, you can join Medium, NewsBreak, and Vocal as a creator to find your voice, reach out to a broad audience, and monetize your content.

You may also check my blog posts about my articles and articles of other writers contributing to my publications on Medium. I share them on my website digitalmehmet.com. Here is my professional bio. You can contact me via weblink.

As a writer, blogger, content developer, and reader, you might join Medium, Vocal Media, NewsBreak, Medium Writing Superstars, Writing Paychecks, WordPress, and Thinkers360 with my referral links. This post includes affiliate links.

You might join my six publications on Medium as a writer by sending a request via this link. 19K+ writers contribute to my publications. You might find more information about my professional background.

You may join Medium with my referral link.

Books
Writing
Book Review
Publishing
Authors
Recommended from ReadMedium