Dealing with .env.local in a next.js TypeScript file: best practices


import GithubProvider from "next-auth/providers/github"
import GoogleProvider from "next-auth/providers/google"

const GITHUB_ID: string = process.env.GITHUB_ID as string;
const GITHUB_SECRET: string = process.env.GITHUB_SECRET as string;
const GOOLE_ID: string = process.env.GOOGLE_ID as string;
const GOOGLE_SECRET: string = process.env.GOOGLE_SECRET as string;

if (typeof GITHUB_ID !== "string") {
    throw new Error("GITHUB_ID is not a String! check your env file")
}
if (typeof GITHUB_SECRET !== "string") {
    throw new Error("GITHUB_SECRET is not a String, check your env file")
}
if (typeof GOOLE_ID !== "string") {
    throw new Error("GOOLE_ID is not a String, check your env file")
}
if (typeof GOOGLE_SECRET !== "string") {
    throw new Error("GITHUB_ID is not a String, check your env file")
}



export const options = {
    providers: [
        GithubProvider({
            profile(profile) {
                console.log("Profile Github", profile)
                return {
                    ...profile,
                    id: profile.sub, 
                }
            },
            clientId: GITHUB_ID,
            clientSecret: GITHUB_SECRET
        }),
        GoogleProvider({
            profile(profile) {
                console.log("Profile Google", profile)
                return {
                    ...profile,
                    id: profile.sub,
                }
            },
            clientId: GOOLE_ID,
            clientSecret: GOOGLE_SECRET,
        })
    ]
}

I am currently facing an issue with declaring environment variables as strings in the clientID and clientSecret . Initially, I encountered a type error where process.env.GITHUB_ID was showing as 'string | undefined' and could not be assigned to clientID which requires a 'string' type. I am open to suggestions for a better approach to handling this issue.

I have attempted converting process.env.GITHUB_ID to a string using other methods, but none seem to resolve the problem effectively.

Answer №1

Since you are already declaring the environment variables yourself, there is no need to check if they exist or not. You can completely remove this section:

if (typeof GITHUB_ID !== "string") {
    throw new Error("GITHUB_ID is not a String! check your env file")
}
if (typeof GITHUB_SECRET !== "string") {
    throw new Error("GITHUB_SECRET is not a String, check your env file")
}
if (typeof GOOLE_ID !== "string") {
    throw new Error("GOOLE_ID is not a String, check your env file")
}
if (typeof GOOGLE_SECRET !== "string") {
    throw new Error("GITHUB_ID is not a String, check your env file")
}

To resolve the TypeScript error, you can declare the variables in the following way:

const GITHUB_ID = process.env.GITHUB_ID!;
const GITHUB_SECRET= process.env.GITHUB_SECRET!;
const GOOLE_ID= process.env.GOOGLE_ID!;
const GOOGLE_SECRET= process.env.GOOGLE_SECRET!; 

Simply copy and paste this code and let me know if you encounter any further issues.

Answer №2

Your application should have these environment variables by default, unless specified otherwise in your env file. Without them, your app won't function properly. Next-auth will handle incorrect environmental inputs on its own.

In this scenario, you can directly specify the clientId and clientSecret like so:

clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,

This approach is also outlined in the next-auth v4 documentation.

If you're using auth.js, which corresponds to version 5 of next-auth, you don't need to explicitly mention clientId and clientSecret if your environment variables match the predefined names in the auth.js documentation.

For GitHub and Google providers, it would look something like this:

AUTH_GITHUB_ID={CLIENT_ID}
AUTH_GITHUB_SECRET={CLIENT_SECRET}

AUTH_GOOGLE_ID={CLIENT_ID}
AUTH_GOOGLE_SECRET={CLIENT_SECRET}

Additionally, here's how I prefer to manage environmental variables with TypeScript:

const GITHUB_ID: string = process.env.GITHUB_ID || ""

This is because environment variables are only present if they are defined in the .env files or if the deployment was done correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a Python script be executed asynchronously in a TypeScript fashion?

Currently, I have a Python script that sends an http request to a microservice, and the request typically takes 3 seconds to complete. Here is a summary of my Python script: def main(): response = request_to_MS(url) # This part of the process doesn& ...

Utilizing generics within a function

Can you help me understand why I am getting an error message that says "Type 'AbstractPopup' is not assignable to type T" when using the return statement in the popupFactory(...) method? This code is just a test example for learning how generics ...

What are some strategies for enhancing TypeScript/Node speed in VSCode with the help of WSL2 and Docker?

My development environment consists of VSCode running on Windows (v1.58.2) with the Remote WSL extension (v0.58.2). I have Docker Desktop (3.5.2, engine: 20.10.7) set up to work with Linux containers through the WSL2 backend. Within these containers, I a ...

The functionality of "exportTrailingSlash: true" is not performing as intended, causing links to not properly redirect to the

I am currently working with nextjs and attempting to perform a static export. My configuration in the next.config.js file is as follows: module.export = { exportTrailingSlash: true, } During development, I write links without the suffix. For example, ...

The Vercel public domain is not functioning as expected

After successfully developing a next.js application with user auth using NextAuth and deploying it to Vercel, I encountered an issue related to the notifications page functionality. The problem arises when the app checks for an active session; if none is f ...

Running a Strapi instance on another developer's system involves cloning the project from Git and launching it successfully

⠼ Loading Strapi[ERROR] Oops! There appears to be an unexpected error. Please try again with --debug for additional information. ┌──────────────────────────────────────── ...

Adding Dependencies to a Static Factory in Typescript

I have developed a service in typescript as a Class. Within this class, I have defined a static Factory where dependencies are injected. However, when I compress my application, the dependencies get compressed too, leading to an undefined provider error. ...

Whenever the afterAuth clerk middleware is invoked with the parameters auth and req, the authentication status is consistently set to signed

Hey everyone, I'm having some trouble setting up clerk in Nextjs14. In my middleware, I have the following: ... afterAuth(auth, req, _) {} ... But when I try to call auth.userId, it returns null and redirects to the sign-in route. However, once it re ...

Tips for correctly registering a button click event in React

I am struggling to correctly type an event in TypeScript in order to get the name of a button upon clicking it. No matter what I try, I keep getting errors. Can anyone help me solve this issue? const handleSortReports= (event : ??? ) => { const ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

Encountered an issue while executing the next build process

Every time I run npm next build, it throws an error message. Despite my efforts to search for a solution online and installing the "extract-text-webpack-plugin," the issue persists. The error being thrown is as follows: > next build (node:8136) Depre ...

Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page. The active messages tab is functioning perfectly without any issues. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message w ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

The Next.js form is having trouble submitting when clicked

I've been experimenting with the react-hook-form by shadcn and have successfully set up the inputs and selects I need from the documentation. However, the onSubmit function that I created doesn't seem to be working as expected. Any idea why? &qu ...

Float32Array should always have a byte length that is a multiple of 4 to avoid any unhandled runtime errors

I am struggling to fetch my custom model in my next.js app. Both the model.json file and the group1-shard1of61 are located in the same folder inside the API directory. I am encountering the following errors: Unhandled Runtime Error RangeError: byte length ...

Updating the data type of the Request object following the execution of the checkAuth middleware in Types

I'm relatively new to TypeScript and recently encountered an issue with extending the Request type. Although I managed to find a workaround, it doesn't sit well with me and I believe there may be a more optimal solution out there. Let's del ...

What is the method in AngularJS2 for using TypeScript to inject dependencies into components?

I have been encountering different methods of injecting dependencies into my component and not all of them seem to be working for me. I am curious about the advantages and disadvantages, what the recommended best practices are, and why some methods are not ...

Implementing query parameters in a Deno controller

I developed a couple of APIs for a Deno Proof of Concept. This is the route implementation: const router = new Router() router.get('/posts', getPosts) .get('/posts/:id', getPostsById) In the second route, I successfully retriev ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

Do changes in Input fields reflect in the parent component?

I was under the impression that I could share data with child components using @Input() directive and communicate data back to the parent component with @Output() along with the appropriate emit. However, I recently discovered that modifications made to th ...