#Run NextJS as function

1 messages · Page 1 of 1 (latest)

green imp
#
import Dirname from "shared/dirname";
import FileLoader from "shared/file-loader";

import Game from "game";
import Website from "website";

(async () => {
    await FileLoader.init(`${Dirname}/global`, async(filepath) => {
        await import(filepath);
        console.log(`[global] loaded ${filepath.split("\\").pop()?.split(".")[0]}`);
    });
    new Game().listen("localhost", 5589).then(() => console.log("Server started!")); // Node.Net TCP Server - Game
    new Website().listen("localhost", 3000).then(() => console.log("Website started!")); // Next.js - Website
})();

I want to run the nextjs website like this, because i want to use the global variables on both side

devout capeBOT
#

Hi @green imp. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, it seems you want to run your Next.js application and have access to global variables on both the server and client side.

In Next.js, you can use environment variables to manage your global variables. By default, environment variables are only available on the server. If you want to expose an environment variable to the browser, you need to prefix it with NEXT_PUBLIC_. These public environment variables will be inlined into the JavaScript bundle during next build source (https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#runtime-environment-variables).

Here's an example of how you can use environment variables in your Next.js application:

import { unstable_noStore as noStore } from 'next/cache'
 
export default function Component() {
  noStore()
  // cookies(), headers(), and other dynamic functions
  // will also opt into dynamic rendering, meaning
  // this env variable is evaluated at runtime
  const value = process.env.MY_VALUE
  // ...
}

To run your Next.js application, you can use the npm run dev or pnpm run dev command source (https://vercel.com/templates/next.js/beam-internal-blog) source (https://vercel.com/templates/next.js/semantic-image-search).

However, the code you provided seems to be trying to run a Next.js application alongside a game server. While it's possible to run a Next.js application from a custom server, the specifics of how to do this would depend on the details of your game server and how it's set up. Unfortunately, the provided knowledge sources do not contain enough information to provide a detailed guide on how to do this.

#

For more information on running a Next.js application from a custom server, you can refer to the Next.js documentation on custom server (https://nextjs.org/docs/advanced-features/custom-server).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

green imp
#

@devout cape i want to run the nextjs like expressjs run it using the listen function.

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To run Next.js like Express.js using the listen function, you can create a custom server for your Next.js application. Here's an example of how you can do this:

const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on <http://localhost:3000'>);
  });
});

In this example, an Express.js server is created and Next.js is told to handle all requests. The server listens on port 3000. This code would typically be placed in a file named server.js in the root of your project.

Please note that a custom server will remove important performance optimizations, like serverless functions and automatic static optimization. You should only use a custom server if you have a specific need that Next.js's built-in server routing does not cover.

For more information, you can refer to the Next.js documentation on custom servers (https://nextjs.org/docs/advanced-features/custom-server).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

green imp
#

hmm, don't use express use node:net

#

@devout cape

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sorry @green imp, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

green imp
devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sorry @green imp, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

green imp
#

@devout cape use node:net instead of expressjs

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Using Node's net module to create a server for a Next.js application is not recommended or supported. The net module is a low-level API for network communication and is not designed to serve HTTP or HTTPS traffic, which is what Next.js requires.

Next.js is built on top of the HTTP/HTTPS protocol, and it expects to receive HTTP requests. The net module operates at a lower level, dealing with TCP/IP sockets, which are not HTTP-specific. This means that you would need to manually parse HTTP requests and format HTTP responses, which is not practical or efficient.

If you want to create a custom server for your Next.js application, it's recommended to use a higher-level HTTP framework like Express.js, as shown in the previous example.

For more information, you can refer to the Next.js documentation on custom servers (https://nextjs.org/docs/advanced-features/custom-server).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

onyx bison
#

how can i use nextauth with nextjs frontend and express backend

green imp
#

@devout cape nextjs custom server, how to change the pages folder path? its not in src/pages but in src/website/pages because the nextjs project is in src/website folder

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To change the pages directory in a Next.js project, you can use the dir option in a custom server setup. However, this is not officially supported by Next.js and may lead to unexpected behavior.

Here's an example of how you can do this with a custom server:

const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, dir: "./src/website" });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    handle(req, res, parsedUrl);
  }).listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on <http://localhost:3000'>);
  });
});

In this example, the dir option is set to ./src/website, which changes the base directory of the Next.js application.

Please note that this is not a recommended or standard way to structure a Next.js application. The standard way is to have the pages directory at the root of your project or inside a src directory. If you structure your project differently, you may encounter issues or limitations.

For more information, you can refer to the Next.js documentation on custom servers (https://nextjs.org/docs/advanced-features/custom-server).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

green imp
#

@devout cape does it also change the path of next.config.js?

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

No, changing the dir option in the custom server setup does not change the path of the next.config.js file. The next.config.js file should always be located at the root of your project.

This is mentioned in the Next.js documentation about the src directory:

Config files like package.json, next.config.js and tsconfig.json should remain in the root of your project. source (https://nextjs.org/docs/app/building-your-application/configuring/src-directory)

So even if you change the base directory of your Next.js application, you should still keep the next.config.js file at the root of your project.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

green imp
#

@devout cape i want to also change the location of the config file

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Unfortunately, the next.config.js file must be located at the root of your project directory. This is a requirement of Next.js and cannot be changed. The Next.js framework looks for the next.config.js file in the project root during the build process.

As stated in the Next.js documentation:

Next.js can be configured through a next.config.js file in the root of your project directory (for example, by package.json) with a default export. source (https://nextjs.org/docs/app/api-reference/next-config-js)

If you need to have different configurations for different parts of your application, you might consider splitting your application into multiple Next.js applications, each with its own next.config.js file. However, this would also mean running multiple build processes and servers, which may not be ideal for your use case.

If you have a specific need to change the location of the next.config.js file, you might want to consider opening a feature request in the Next.js GitHub repository (https://github.com/vercel/next.js).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

onyx bison
devout capeBOT
#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

green imp
# onyx bison hmm its a bit confusing for me i just want to use nextauth from my nextjs front...
const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.use(auth); // middleware
  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on <http://localhost:3000'>);
  });
});
onyx bison
green imp
onyx bison
#

in nextauth v5

green imp
green imp
#

??

green imp
green imp
green imp
#

@devout cape how to access the global variables to my page?

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js, you can use environment variables to manage your global variables. Here's how you can do it:

  1. Define your environment variables in a .env.local file at the root of your project. For example:
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

This will load process.env.DB_HOST, process.env.DB_USER, and process.env.DB_PASS into the Node.js environment automatically, allowing you to use them in your Next.js application source (https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#loading-environment-variables).

  1. Access the environment variables in your Next.js pages or components using process.env. For example:
export async function getStaticProps() {
  const db = await myDB.connect({
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
  })
  // ...
}

By default, environment variables are only available on the server. If you want to expose an environment variable to the browser, you need to prefix it with NEXT_PUBLIC_. For example, NEXT_PUBLIC_ANALYTICS_ID. These public environment variables will be inlined into the JavaScript bundle during next build source (https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#runtime-environment-variables).

Please note that after being built, your app will no longer respond to changes to these environment variables. All NEXT_PUBLIC_ variables will be frozen with the value evaluated at build time source (https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser-part-1).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@green imp kapa.ai is still learning and improving, please let us know how it did by reacting below

green imp
#
export async function getStaticProps() {
    const user = await Database.query.users.findFirst({ where(fields, operators) {
        return operators.eq(fields.id, 1)
    }})
}

export default function A() {
    return <div>{user?.Name}</div>;
}

@devout cape how to use it? is this correct?

devout capeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The code you provided seems to be trying to fetch a user from a database in the getStaticProps function and then display the user's name in a component. However, it's not correctly passing the fetched user data to the component.

In Next.js, you can fetch data in getStaticProps and then pass it to your page component via props. Here's how you can do it:

export async function getStaticProps() {
  const user = await Database.query.users.findFirst({ where: { id: 1 } })

  // Must return an object with the props key
  return { props: { user } }
}

export default function A({ user }) {
  // Now user is available as a prop
  return <div>{user?.Name}</div>;
}

In this corrected code, the getStaticProps function fetches a user from the database and then returns an object with a props key. The value of the props key is an object that contains the fetched user data. This data is then passed to the A component as a prop source (https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props#using-getstaticprops-to-fetch-data-from-a-cms).

Please note that the getStaticProps function is run at build time, so it's only suitable for data that can be publicly cached and doesn't change on every request. If you need to fetch data that changes frequently or is user-specific, you might want to use getServerSideProps or getInitialProps instead source (https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props#when-should-i-use-getstaticprops).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: