# JWT Auth Does Not Work Heroku

**URL:** <https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245>\
**Category:** Curriculum Help\
**Tags:** backend\
**Created:** [August 13, 2022, 6:41am UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245 "2022-08-13T06:41:26Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![modimo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/modimo/32/81291_2.png) [@modimo](https://forum.freecodecamp.org/u/modimo)\
**Post date:** [August 13, 2022, 6:41am UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/1 "2022-08-13T06:41:26Z")

</div>

When I sign up or sign in on my nodejs application, I generate a jwt token but what happens after is I have an api that verifies that token but that api only works on postman and not heroku. I am unsure of why that is. It just gives me a 401 error.

auth.js

```auto

//check if user is authenticated
exports.isAuthenticated = async (req,res,next) => {
    const {token} = req.cookies;
    //make sure token exists
    if (!token) {
        return next (new ErrorResponse('You must log in to access this resource okay yeah', 401));
    }
    try {
       //verify token
       const decoded = jwt.verify(token, process.env.JWT_SECRET);
       req.user = await User.findById(decoded.id);
       next();
    } catch (error) {
        return next (new ErrorResponse('You must log in to access this resource okay dude', 401));
    }
}

```

---

<div class="post-metadata">

**Author:** ![lasjorg](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/lasjorg/32/280761_2.png) [@lasjorg](https://forum.freecodecamp.org/u/lasjorg)\
**Post date:** [August 13, 2022, 2:16pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/2 "2022-08-13T14:16:43Z")

</div>

Did you add the `JWT_SECRET` variable to the Heroku config vars?

---

<div class="post-metadata">

**Author:** ![modimo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/modimo/32/81291_2.png) [@modimo](https://forum.freecodecamp.org/u/modimo)\
**Post date:** [August 13, 2022, 4:33pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/3 "2022-08-13T16:33:36Z")

</div>

Yes I did add that variable to the config variables. I seem to get a cors error that prevents it

> \*\* No ‘Access-Control-Allow-Origin’ header is present on the requested resource.\*\*

but I thought I had code to deal with it.

index.js

```auto
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
  });

```

---

<div class="post-metadata">

**Author:** ![lasjorg](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/lasjorg/32/280761_2.png) [@lasjorg](https://forum.freecodecamp.org/u/lasjorg)\
**Post date:** [August 13, 2022, 9:44pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/4 "2022-08-13T21:44:13Z")

</div>

Try using the cors package and see if that works. I assume your middleware is running before all the routes?

---

<div class="post-metadata">

**Author:** ![modimo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/modimo/32/81291_2.png) [@modimo](https://forum.freecodecamp.org/u/modimo)\
**Post date:** [August 14, 2022, 10:08pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/5 "2022-08-14T22:08:33Z")

</div>

I have the middleware before my routes.

index.js

```auto

const express = require("express");

const app = express();
const PORT = process.env.PORT || 8500
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const errorHandler = require("./middleware/error");
const cors = require('cors');

//setting cors
const corsOptions = {
//my origin
    origin: '*'
  }

//Import Routes
const Routes = require('./routes/routes');

dotenv.config();

//middleware
app.use(cors(corsOptions));
app.use(express.json());
app.use(helmet());
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(cookieParser());
app.use("/api", Routes);

//welcome message 
app.get('/', (req,res) => {
    console.log("Welcome to the API.")
});

app.get('/greeting', (req,res) => {
    res.json({greeting: 'Hello there'})
});

mongoose.connect(process.env.MONGO_URL, {useNewUrlParser: true, useUnifiedTopology: true}).then(() => {
    console.log("MongoDB Connected")
})
.catch((err) => console.log(err));

app.listen(PORT, ()=> {
    console.log("Backend server is running!")
})

```

Okay so it says I need to add a “no-cors” method to the fetch method I have which is in my frontend but I am not sure how to do it and get it working.

Original

```auto
useEffect(()=>{
    fetch(process.env.REACT_APP_USER)
    .then(res => {
      return res.json()
    })
    .then(result=>{
      console.log(result);
      setProfile(result.user);
    })
    .catch(error => {
      console.log(error);
    })
},[]);

```

My attempt

```auto
useEffect(()=>{
    const data = fetch(process.env.REACT_APP_USER, {
      mode: 'no-cors'
    })
    .then(res => {
      return res.json()
    })
    .then(result=>{
      console.log(result);
      setProfile(result.user);
    })
    .catch(error => {
      console.log("this is the error for getme" ,error);
    })
    return data.json()
},[]);

```

---

<div class="post-metadata">

**Author:** ![lasjorg](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/lasjorg/32/280761_2.png) [@lasjorg](https://forum.freecodecamp.org/u/lasjorg)\
**Post date:** [August 15, 2022, 1:08am UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/6 "2022-08-15T01:08:46Z")

</div>

You shouldn’t use the no-cors mode, it returns an opaque response.

> [Fetch Standard](https://fetch.spec.whatwg.org/#fetch-method)
> 
> “`no-cors`”: Restricts requests to using [CORS-safelisted methods](https://fetch.spec.whatwg.org/#cors-safelisted-method) and [CORS-safelisted request-headers](https://fetch.spec.whatwg.org/#cors-safelisted-request-header). Upon success, fetch will return an [opaque filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque).

> [Fetch Standard](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque)
> 
> An opaque filtered response is a [filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response) whose [type](https://fetch.spec.whatwg.org/#concept-response-type) is "`opaque` ", [URL list](https://fetch.spec.whatwg.org/#concept-response-url-list) is the empty list, [status](https://fetch.spec.whatwg.org/#concept-response-status) is 0, [status message](https://fetch.spec.whatwg.org/#concept-response-status-message) is the empty byte sequence, [header list](https://fetch.spec.whatwg.org/#concept-response-header-list) is empty, and [body](https://fetch.spec.whatwg.org/#concept-response-body) is null.

> <https://stackoverflow.com/questions/39109789/what-limitations-apply-to-opaque-responses>

* * *

Not sure why you can’t fetch from your own API. Does commenting out the helmet middleware do anything?

Is the URL you are fetching against an HTTPS URL?

Is your frontend on Netlify? (I seem to remember you moving it to that).

You might try using

> **[Rewrites and proxies](https://docs.netlify.com/routing/redirects/rewrites-proxies/#proxy-to-another-service)**
>
> Use rewrite rules to fetch a location behind the scenes while the URL in the visitor’s address bar remains the same. Proxy to another service or site.

But I really do not think that should be needed if the backend is set up correctly and you are not fetching from HTTPS to an HTTP endpoint

---

<div class="post-metadata">

**Author:** ![modimo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/modimo/32/81291_2.png) [@modimo](https://forum.freecodecamp.org/u/modimo)\
**Post date:** [August 15, 2022, 3:40am UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/7 "2022-08-15T03:40:47Z")

</div>

I commented out the helmet and that did not work. I also tried a \_redirect file which is basically like the netlify.toml file and that did not succeed.

(still get the same cors error : No ‘Access-Control-Allow-Origin’ header is present on the requested resource.).

All the urls I am doing a request to on heroku are https. My frontend is on netlify, and I am fetching from an https to an https endpoint.

---

<div class="post-metadata">

**Author:** ![modimo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/modimo/32/81291_2.png) [@modimo](https://forum.freecodecamp.org/u/modimo)\
**Post date:** [August 15, 2022, 10:55pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/8 "2022-08-15T22:55:21Z")

</div>

Any other suggestion would be greatly appreciated.

---

<div class="post-metadata">

**Author:** ![lasjorg](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/lasjorg/32/280761_2.png) [@lasjorg](https://forum.freecodecamp.org/u/lasjorg)\
**Post date:** [August 16, 2022, 5:32pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/9 "2022-08-16T17:32:21Z")

</div>

Do you have a repo for this so we can see all the code?

* * *

I assume this has to do with using a cookie for JWT.

1. Add the `sameSite` option to the cookie res.

```auto
res
  .cookie('token', token, {
    httpOnly: true,
    secure: true,
    sameSite: 'none',
  })
  .send();

```

1. Add the origins to cors (not `*`) and set `credentials: true` (the URL should not have a trailing slash)

```auto
app.use(
  cors({
    origin: [
      "http://localhost:3000",
      "https://yourfontend.netlify.app",
    ],
    credentials: true,
  })
);

```

1. Set `credentials: 'include'` in the [fetch options](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#sending_a_request_with_credentials_included) (or use Axios with defaults `axios.defaults.withCredentials = true`)

* * *

Article

> **[Sharing cookies with JWTs across different domains and ports](https://jaygould.co.uk/2021-08-20-sharing-cookies-jwt-between-different-domains/)**
>
> When using Fetch, cookies are not shared between sites with different origins, including domains, subdomains, and even ports. Here's why, and the solution.

Here is an example repo I found you can look at. I tested it with Heroku and Netlify and it works for me.

`https://github.com/jgbijlsma/mern-auth-template-tutorial`

---

<div class="post-metadata">

**Author:** ![modimo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/modimo/32/81291_2.png) [@modimo](https://forum.freecodecamp.org/u/modimo)\
**Post date:** [August 16, 2022, 10:55pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/10 "2022-08-16T22:55:03Z")

</div>

I am still getting the same cors error. I will provide my github repo though.

> **[GitHub - typeveron/map-pins-deploy](https://github.com/typeveron/map-pins-deploy)**
>
> Contribute to typeveron/map-pins-deploy development by creating an account on GitHub.

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 7, 2025, 3:43pm UTC](https://forum.freecodecamp.org/t/jwt-auth-does-not-work-heroku/542245/11 "2025-01-07T15:43:51Z")

</div>

Closed on January 7, 2025, 3:43pm UTC


