Hello @Jihoo Byeon
To access Azure SQL Database connected with Azure Static Web Apps from Next.js, you can create an API route in Next.js that fetches data from the database and returns it to the client.
Based on the error you mentioned, it seems like there might be a routing issue with your Next.js app. By default, Next.js treats any file in the pages
directory as a page.
To avoid this, you can create a pages/api
directory and put your API routes there. This will ensure that Next.js treats them as API routes and not pages. Here's an example of how you can create an API route in Next.js to fetch data from Azure SQL Database:
- Create a new file in the
pages/api
directory calleddata-api.js
. - In
data-api.js
, import themssql
package and create a connection to your Azure SQL Database. Here's an example:
import sql from 'mssql';
const config = {
server: '.database.windows.net',
database: '',
user: '',
password: '',
options:
{
encrypt: true,
enableArithAbort: true
}
};
export default async function handler(req, res)
{
try
{
// Create a new connection pool
const pool = await sql.connect(config);
// Query the database
const result = await pool.request().query('SELECT * FROM ');
// Return the result as JSON
res.json(result.recordset);
} catch (err)
{
console.error(err); res.status(500).send('Error connecting to database');
} }
- In your Next.js app, you can fetch data from this API route using the
fetch
API.